Files in Azure file share can only be opened as read-only on one specific Profile on Windows 10 - (DFS-N with Domain Based Authentication)

Question: [I will start by explaining how the Environment is setup]
For the File share We use DFS-N mapping, EX- \\Domain.local\Storageaccount. This mapping is hosted with DFS-N role on  a Windows Server 2012 R2 server.
On the DFS-N server, the folder that I am working is actually on azure for example, - \\Domain.local\Storageaccount\FolderA\SubforbderB --> This folder has a target pointed at \\storageaccount.file.core.windows.net.
There is a tunnel to Azure. The authentication is domain based authentication. So user access the \\Domain.local\Storageaccount\ with domain AD authentication and return the Kerberos ticket to Azure file and authenticate against Azure as well.
Now the odd thing here is, I do have a workaround, which is to map this folder directly with Azure file share path instead of AD path \\storageaccount.file.core.windows.net\FolderA\SubforbderB - this worked perfectly fine and user can open file with read-write access. which means the issue is with AD authentication. This issue doesn't happen on any other folder, which are setup in this same way but without inheritance, no other users have this issue.
[Now I will explain the issue]
Currently we have a folder \\Domain.local\Storageaccount\FolderA\SubforbderB - SubforbderB - This folder has inheritance turned OFF. We are explicitly assigning permissions. UserA is having issue accessing the files inside the \\Domain.local\Storageaccount\FolderA\SubforbderB folder, which file he opens it opens as read-only. UserA has full control as per NTFS as well as IAM RBAC roles. I did test UserA account on a different computer and confirmed the account does have read-write access. I tested UserB account with same access as UserA on a different user profile on the same Windows 10 computer, and UserB can access the files with read-write. This proves to me the issue is with the current user profile on the Windows 10 computer.
We are aware that we can simply re-create the profile on the Windows computer and backup and restore the data and this issue will be resolved. However, the user has a lot of custom user specific configurations, and it will be difficult to move to a new profile.
We worked with Microsoft Azure team and Windows team and they are not providing any solution other that recreating the profile.
I hope one of you have ran into this issue and resolved it in the past.
Here are the things we tried: Clear credentials manager, re-join domain,  SFC, DISM scan, Windows Updates, looked for any file explorer map specific registry, cleared those as well.
Do you have any suggestion other than recreating the Windows user profile?
Answer: We had a On-prem DC at this location, Somehow after we decommission this DC and now the Clients are authenticating directly with the DC in Azure. I re-applied the NTFS permission using the "ACCESS KEY". Now everything is working as expected
Answer: Maybe you need to assign the Storage File Data Share Contributor Azure RBAC role, or a custom role with the following data actions. As shown below, for write
Microsoft.Storage/storageAccounts/fileServices/fileshares/files/write
{
  "assignableScopes": [
    "/"
  ],
  "description": "Allows for read, write, and delete access in Azure Storage file shares over SMB",
  "id": "/providers/Microsoft.Authorization/roleDefinitions/0c867c2a-1d8c-454a-a3db-ab2ea1bdc8bb",
  "name": "0c867c2a-1d8c-454a-a3db-ab2ea1bdc8bb",
  "permissions": [
    {
      "actions": [],
      "notActions": [],
      "dataActions": [
        "Microsoft.Storage/storageAccounts/fileServices/fileshares/files/read",
        "Microsoft.Storage/storageAccounts/fileServices/fileshares/files/write",
        "Microsoft.Storage/storageAccounts/fileServices/fileshares/files/delete"
      ],
      "notDataActions": []
    }
  ],
  "roleName": "Storage File Data SMB Share Contributor",
  "roleType": "BuiltInRole",
  "type": "Microsoft.Authorization/roleDefinitions"
}

By the way, for user profile shares, I would recommend FSLogix. FSLogix utilizes profile containers to encapsulate user profiles. These containers are dynamically attached to user sessions, allowing users to have a consistent experience across different sessions. Profile containers store user-specific data, configurations, and settings, reducing logon times and improving performance.
PowerShell to get the acl
# Specify the path to the file or folder
$path = "C:\Path\To\Your\FileOrFolder"

# Get the NTFS ACL
$ntfsAcl = Get-Acl -Path $path

# Display the NTFS ACL
Write-Host "NTFS ACL:"
$ntfsAcl | Format-List

Comment: Thank you for responding, Storage File Data Share Contributor Azure RBAC is the Default share level access on this storage account, and we confirmed it works on another computer for this user, which makes me think this is more of a caching issue on the windows computers.
Comment: Is it a premium storage account? Have you already looked at the acl with the powershell command is there is a explicity assigned to write you can use the Get-Acl for that. Windows doesn't cache the ACL. And do you have the same issue when you directly map the Azure file share as a mapped drive? Please try to assign the role directly instead of relying on the default share access
Comment: Enable logging and monitoring for both DFSN and Azure File Shares to capture detailed information about access attempts, errors, and any issues that might occur.
Comment: Yes, we do have directly assigned write access through RBAC as well. When we map the azure share with fqdn the issue doesn't occur, the issue only happens if it is mapped using the DFS-N. But on a different computer that is onsite, i logged in with the users account, and it works without issue. So i wonder maybe its becuase the user is remote and connecting with VPN,  maybe the Authentication to AD needs to happen atleast once onprem instead of the VPN? On this same computer that the user is onsite, i logged in with another Domain account and it works fine as well on this same folder.
Comment: \\storageaccount.file.core.windows.net\FolderA\SubforbderB - This mapping works but \\Domain.local\Storageaccount\FolderA\SubforbderB this method doesn't work, and as per reading MS doct, when i map with DFS-N it authenticated with AD first then pass the response to Azure
Comment: This issue is only happening on specific folder, that has inheritance turned OFF on the NTFS, but other people who has same access as him doesn't have issue accessing files in this folder with write access
Comment: .local are non routable domains and are not supported in Azure. Have you looked at his effective permissions? Maybe use a tool like accesenum from sysinternals.
Comment: Maybe because of the local the identity doesn't get translated properly and the acl isn't correctly passed through. Also Enable logging and monitoring for both DFSN and Azure File Shares to capture detailed information about access attempts, errors, and any issues that might occur. @work


Identify row with maximal value in each column of the dataframe in r

Question: I have a table like this:
d=structure(list(sample = c("A", "B", "C", "D", "E"), Obs1 = c(10L,
0L, 11L, 2L, 3L), Obs2 = c(0L, 0L, 2L, 1L, 10L), Obs3 = c(1L,
1L, 1L, 1L, 10L), Obs4 = c(0L, 11L, 3L, 3L, 3L), Obs5 = c(7L,
7L, 3L, 3L, 3L)), class = "data.frame", row.names = c(NA, -5L
))

For each column i'd like to find row with maximal value in this column to get in result a table like (for my example):

How can i achieve that in R (preferably in Base library).
Comment: You should be able to modify [this previous answer to the question "For each row return the column name of the largest value"](https://stackoverflow.com/questions/17735859/for-each-row-return-the-column-name-of-the-largest-value) to make this work for your question.
Answer: Use apply twice:
data.frame(sample = apply(d[-1], 2, function(x) toString(d[x == max(x), 1])),
           max = apply(d[-1], 2, max))

giving this data.frame:
     sample max
Obs1      C  11
Obs2      E  10
Obs3      E  10
Obs4      B  11
Obs5   A, B   7

Comment: You can use either d expression. They refer to the same thing. x==max(x) is a logical vector which is TRUE for those positions where x equals the maximum x.  Then we take those rows for which it is TRUE and just column 1.
Comment: Thanks! That works for me. Let me please a few questions, because your code is too advanced for me? Why `d[-1] not d[,-1]`?I'm wondering, what does that part `d[x == max(x), 1]` do in details?


First variation of $\int_\Omega |\nabla u |^p$

Question: How can I calculate the first variation of $F(u) = \int_\Omega |\nabla u |^p$?
I cannot expand $|\nabla (u+th)|^p = (|\nabla u |^2 + t^2|\nabla h|^2 + t\nabla u \nabla h)^{\frac p2}$ at all so I don't know how to simplify!!
Comment: Yes, it is rigourous as long as you also justify the **differentiation under the integral sign** (see http://en.wikipedia.org/wiki/Leibniz_integral_rule#Measure_theory_statement).
Comment: Do not simplify. Take the derivative w.r.t. $t$.
Comment: But is it rigourous if I do that? I wanted to show it using the Gateaux derivative formula
Answer: Let $J(u) = \int_{\Omega} |\nabla u|^p\, dx$. Then
\begin{align}\frac{J(u + th) - J(u)}{t} &= \frac{1}{t}\int_{\Omega} (|\nabla(u + th)|^p - |\nabla u|^p)\, dx\\
&= \frac{1}{t} \int_{\Omega} \int_0^1 \frac{d}{ds} |\nabla(u + sth)|^p\, ds\, dx\\
&= \frac{1}{t} \int_{\Omega} \
\int_0^1 p|\nabla u + st\nabla h|^{p-2}(\nabla u + st \nabla h)\cdot (t\nabla h) \, ds\, dx\\
&= \int_{\Omega} \int_0^1 p|\nabla u + st\nabla h|^{p-2}(\nabla u \cdot \nabla h)\, ds\, dx + O(t)
\end{align}
Taking the limit as $t \to 0$ results in
$$J'(u)(h) = \int_\Omega p|\nabla u|^{p-2}\nabla u \cdot \nabla h\, dx.$$
Comment: Thangs a lot kobe


How to keep MEAN (stack) running?

Question: I'm using grunt to run the MEAN project on Ubuntu, but when I close the putty (I use putty to connect Ubuntu server from my PC), it would close the program too.
My question is how can I keep MEAN running?
Update: nohub grunt & stops after I close putty
Answer: There are various node based process managers which can serve your task. My favorite is pm2 (http://pm2.keymetrics.io/)
Package managers allow your program to keep running even in case of hiccups. They can watch your project directories for any changes that you might push to them and restart servers based on those changes.
Other favorite is forever (https://www.npmjs.com/package/forever).
Answer: you need to run the command in background and I would also recommend to use nohup so:
nohup grunt &

should do the trick.
https://en.wikipedia.org/wiki/Nohup
Comment: `nohub grunt &` stops after I close putty
Comment: @DotKu nohup instead of nohub!
Comment: Sorry, it was my typo, but I mean `nohup`
Answer: NODE_ENV=staging nohup node appStag.js &
 You can use the above command to run node server
 and you can get the above environment using process.env.NODE_ENV
Answer: I found a npm package called forever is a good solution, I use forever to run the program right now; and it works perfect with putty.

How to keep MEAN (stack) running?


Heroku Rails 4 assets não carregam

Question: Depois que fiz o deploy esses arquivos abaixo não estão sendo carregados.

Este é meu diretório

Este é meu application.rb

Aqui como eles estão sendo chamados
<%= stylesheet_link_tag "home" %>
<%= javascript_include_tag "home" %>

<img class="client" src="<%= asset_path('b.png') %>">

update:
Percebi não são só esses assets listados, nenhum asset está carregando.
Answer: Resolvido
Os erros estavam dentro dos arquivos scss.erb. Eles não chamavam corretamente os helpers do rails image_tag e asset_path.
Meus arquivos scss.erb estava como abaixo.
Errado
background: url(<%= image_path 'fake_slider.png' %>) no-repeat 0 0;

Jeito certo
Coloquei eles dentro de aspas duplas " " e depois tudo funcionou
background: url("<%= image_path 'fake_slider.png' %>") no-repeat 0 0;

Heroku Rails 4 assets não carregam


Deriving possible values of a,b, and c from a system of equations

Question: In a math problem I arrive at the following system of equations but struggle to solve any variable (in terms of the other two):
$$
2ab + c - 2c^2 = 0
\\
2bc + a - 2a^2 = 0
\\
2ac + b - 2b^2 = 0
\\
a + b + c = 2
$$
Please kindly advise any next step, possibly involving algebraic manipulation of any two equations, to find possible values of $(a, b, c)$.
Comment: Negate the first three and add them.  You should find the sum of three squares.
Comment: Subtract the first two equation and factor out $(a-c)$.
Answer: The issue here is that these four equations in three variables are not consistent with each other so there is no solution for $a, b$ and $c$.
For example, if you take three of these equations (which should be sufficient to find solutions since there are three unknowns)
$$2ab+c−2c^2=0$$
$$2bc+a−2a^2=0$$and $$a+b+c=2$$
Then you get either $$(a,b,c)=(0,2,0)$$or $$(a,b,c)=(\frac56, \frac13,\frac56)$$
But both of these sets are inconsistent with the equation previously omitted, i.e. $$2ac+b-2b^2=0$$ which no longer holds for either set.
Similarly, if you start with the first three equations, it is not possible for $a+b+c$ to take the value $2$.


Token in Shortcuts

Question: Does anybody know of a way to use tokens in a shortcut link? Background: I would like to link to a users IMCE Browser at http://DRUPALSITE/user/[current-user:uid]/imce from the shortcuts bar.
Answer: I found a way to solve my problem: The me aliases plugin replaces a defined placeholder (normally "me") with the uid of the current user:
Example: user/me/imce for the admin aliases to user/0/imce.
It's not very flexible though, as it can only replace the uid.

Token in Shortcuts


Trouble with factoring polonomial to the 3rd degree

Question: I am having trouble factoring this problem:
$\displaystyle{-x^{3} + 6x^{2} - 11x + 6}$
I know the answer but i can't figure out how it is done with this.
I have tried by grouping and is doesn't seem to work. Can someone show me how to do this.
Comment: That's not a "problem," it is a polynomial. The problem is factoring the polynomial. That might seem pedantic, but it is important to name things correctly in mathematics.
Answer: Hint: $$-1 + 6 - 11 + 6 = 0$$
This method may be suggested by examining the rational roots theorem, as well.
Answer: $$\begin{align}
& -x^3+6x^2-11x+6 \\
=& -x^3+1+6x^2-11x+5 \\
=& (1-x^3)+6x^2-6x-5x+5 \\
=& (1-x)(1+x+x^2)-6x(1-x)+5(1-x) \\
=& (1-x)(1+x+x^2-6x+5) \\
=& (1-x)(x^2-5x+6) \\
=& (1-x)(x^2-2x-3x+6) \\
=& (1-x)(x(x-2)-3(x-2)) \\
=& (1-x)(x-2)(x-3)
\end{align}$$
Comment: you have an error somewhere
Comment: You may want to edit your answer after reading about [the `align` environment](http://meta.math.stackexchange.com/a/5024/43351) for MathJax.
Comment: There we go. That's a lot more readable.
Comment: @Lord_Farin. Thank you I agree with with you
Comment: You're welcome. Be sure to check the source, so that you can typeset your answers like this yourself in the future!
Answer: Big hint:
In this case, just look for zeros of the cubic polynomial, since each zero tells you a linear factor (by the factor theorem).
Then try looking at factors of 6 (the constant term) - there are not many integer factors of 6 ...


How to get prediction intervals at mean & at max of covariate values in R

Question: I'm still working on R problems from a book, and using my spending data.
Part 1: I need to predict the amount that a male with average data for status, income and verbal would spend along a 95% CI. (NB, male is coded as 0 and female 1 in the data set.)
First I used the linear model newspend<-lm(sepnding ~ status + income + verbal + sex) and from a previous question the sex coefficient is for female, so how would I get the male?
> qt(0.975,42)
[1] 2.018082
> c(-22.12-2.02*8.21,-22.12+2.02*8.21)
[1] -38.7042  -5.5358

First Question:  I don't know how what this means and how will I get a 95% CI for males if this is for females?
Part 2: Then repeat the prediction for males with maximal values of status, income and verbal and determine which CI is wider. Second, I used the max. values for the data in a new equation.
     sex             status          income
 Min.   :0.0000   Min.   :18.00   Min.   : 0.600
 1st Qu.:0.0000   1st Qu.:28.00   1st Qu.: 2.000
 Median :0.0000   Median :43.00   Median : 3.250
 Mean   :0.4043   Mean   :45.23   Mean   : 4.642
 3rd Qu.:1.0000   3rd Qu.:61.50   3rd Qu.: 6.210
 Max.   :1.0000   Max.   :75.00   Max.   :15.000

     verbal          spending
 Min.   : 1.00   Min.   :  0.0
 1st Qu.: 6.00   1st Qu.:  1.1
 Median : 7.00   Median :  6.0
 Mean   : 6.66   Mean   : 19.3
 3rd Qu.: 8.00   3rd Qu.: 19.4
 Max.   :10.00   Max.   :156.0

x0<-data.frame(status=75.00, income=15.00, verbal=10.00, sex=1.00)
I'm not sure if this is how I get the maximal values for a male?
(Or should the 2nd part be a new question since it's a lot of information?)
Comment: You have obtained confidence interval not for females (average spending), but for the difference between males and females (with respect to other features in the model).
Comment: so my prediction is incorrect for what I am trying to determine for the problem. Please clarify....thanks
Answer: Here is how you set up the date for male average spending estimate with CIs:
mavg<-data.frame(status=45.23, income=4.642, verbal=6.66, sex=0.00);

...female average:
favg<-data.frame(status=45.23, income=4.642, verbal=6.66, sex=1.00);

...male max:
mmax<-data.frame(status=75.00, income=15.00, verbal=10.00, sex=0.00);

...female max:
fmax<-data.frame(status=75.00, income=15.00, verbal=10.00, sex=1.00);

The general way to get the predictions given a new dataset is...
predict(newspend,newdata=FOO,interval='conf');

...where FOO is whichever one of your new data.frames you want the results for. Or you can combine them into one data.frame and get all the results at once:
mfavgmax<-rbind(mavg,favg,mmax,fmax);
predict(newspend,newdata=mfavgmax,interval='conf');

Be warned though: your model and your predictions assume that status, income, verbal, and sex all affect spending independently of each other. In real life data is rarely that clean. I would check whether there are significant interaction terms:
install.packages(MASS); # Only need to run this line once
library(MASS);
newspend.aic<-stepAIC(newspend,trace=F,direction='both',scope=list(lower=.~.,upper=.~(.)^4));

Now you can do predict on newspend.aic like you did above. You might have new interaction terms in the model.
Another problem is that status, income, verbal, and sex may be correlated with each other (this is called multicollinearity). So, the population maximum (or average, etc.) for males might be different than for females. At high statuses income mean/max will obviously be different than at lower statuses. For categorical variables like male/female, you can at least get the mean/max for that category and use that for your predictions.
But what if you want to get estimates for spending as status increases continuously form 18 to 75? Sure predict will give you estimates with income and verbal set to any number you like... but income and verbal are not static, they probably correlated with status and with each other... and how to pick reasonable values for these numeric variables for prediction purposes is the question that's stumping me right now and how I happened onto your question.
Hope my answer helps, and it's scary, isn't it, how fast you get to the deep end of the pool with a simple-seeming problem?


Is there is any result claiming that there cannot be any other twin Mersenne primes?

Question: There are 3 known Twin Mersenne Primes: $M3$ and $M5$, $M5$ and $M7$, $M17$ and $M19$. More precisely, if both $M(p)$ and $M(p+2)$ are both prime, then they are called Twin Mersenne Primes.
My question is: Is there is any result claiming that there cannot be any other twin Mersenne primes
Comment: There is no result on whether or not there are infinitely many Mersenne primes, so I would doubt that there is any result on whether or not there are infinitely many **twin** Mersenne primes. To make this case stronger, there is no result even on whether or not there are infinitely many twin primes.
Comment: @barak, OP is not asking whether there are infinitely many, but whether there are *any* (beyond M19).
Comment: @GerryMyerson: True. If there was a large amount of known Mersenne primes (even without a formal proof for an infinite amount of them), then my case would be very weak indeed. But since there are only some $40$ known Mersenne primes, asking whether or not there are any Mersenne twin primes beyond the $7$th Mersenne prime is "rather equivalent" to asking whether or not there is a finite amount of Mersenne twin primes out of the (yet unproven) infinite amount of Mersenne primes. I realize that it's not a "very mathematical" statement, so I hope you can read my point in between the lines.
Answer: p = 3, 5, 17, 107 and 521 are the only numbers known where $2^p - 1$ is a Mersenne prime and p+2 is a prime. Since Mersenne primes are so rare, Mersenne primes where p is a twin prime are even rarer.
I don't know of any particular reason why p+2 shouldn't be a prime and $2^{p+2} - 1$ shouldn't be a Mersenne prime if $2^p - 1$ is a Mersenne prime, so I wouldn't bet my life that there are no other twin Mersenne primes.
On the other hand, the primes p where $2^p - 1$ is a Mersenne prime seem to have an exponential distribution (very roughly the same number with x ≤ p < 10x for every x), so I wouldn't think the chance is more than one in 100,000 that another p exists. The last two known Mersenne primes have p ≈ 58,000,000 and q ≈ 74,000,000, so the chances that p+2 belongs to a Mersenne prime were quite slim.
You could ask whether there are consecutive primes p, q such that $2^p - 1$ and $2^q - 1$ are both Mersenne primes; there are two more examples with p = 2 and p = 13, but still not very likely.
You could ask whether there are more p with $2^p - 1$ a Mersenne prime and p+2 a prime; heuristically there should be infinitely many but they should be so rare that none might ever be found.


How to speed up a MySQL Import

Question: I posted a related question on askubuntu.com, but this may be a better place and way to ask it.
I'm working on a way to speed up a db import. Currently the import is taking a week, give or take a few days, which is unacceptable, and I know it can happen faster (dumping the data from a production server takes under an hour).
I set up a MySQL database as a symlink on a ramdisk I set up using ramfs, which is like a cacheless version of tmpfs. Despite the performance difference between the a hard disk and the RAM, I'm still only seeing between 40-190 QPS.
The table is innodb.
How can I speed up the import?
I seem to be getting a lot of down votes on this question, so perhaps it would be helpful to clarify my intentions:

This is not a production server
I have a system of flushing the ramdisk to disk, and went through the effort to set it up so that I could do it at will
My goal is to be able to import over 8 million records in a reasonable amount of time. Something less than a week would be nice, which is the performance I was getting with the default install of MySQL.
Comment: Why are you setting up a database on a ramfs (you realize you'll lose all the data when the machine reboots, right)? Why do you expect that a database engine (big, complex piece of software) will operate at blistering "DDR3" speeds (you realize for small databases disk access is rarely the bottleneck due to OS and DB server caching, right)?
Comment: You may want to go over to dba.stackexchange.com and visit their chat to see if somone there can give you some advice.
Answer: this is not normally how you setup a database. MySQL does it's own caching to memory. The ideal would be to setup MySQL with loads of memory so it can cache the indexes of the tables to memory, this will speed up look ups and increase the QPS.
BUT, if you have SQL thats not optimised and using indexes correctly you won't be able to increase QPS, not even with faster drives as in your case the faster drives are ram fs.
A couple of things to review from yourside,

How are my tables structured?
NO!!! -> SELECT * FROM ... <- this kills performance
Do I have the correct indexes
Are my busy tables on separate disk volumes
BINLOGS on separate disk volume, INNODB on separate disk volume
VARCHARS = BAD DESIGN

Lastly it's difficult to optimise a database that's not properly designed for the task at hand.
Comment: ultimately I increased the innodb_buffer_pool_size, set innodb_flush_log_at_trx_commit=2, and moved the ibdata1, ib_logfile0, and ib_logfile1 over onto the ramdisk. The import that was taking a week was cut down to less that 20 minutes.

How to speed up a MySQL Import


JQuery Causes Seemingly Endless Loop and page load times of 1 minute + - "Warning: reference to undefined property D.cache[a][d]"

Question: The rendering of my pages on my website have slowed down drastically.  When I turn on the error console I get the image below that shows the error:
Warning: reference to undefined property D.cache[a][d]

You can see a screenshot below:

These warnings continue until the browser memory becomes bloated, the browser locks up, or the page simply takes over a minute to load!

I am at a loss for how to debug this issue b/c when I open the file cited in the warning, it is the long minified jquery script.
How can I go about fixing this issue?
Answer: This is obviously not a problem in Drupal core. This mean the the issue is in one of three places:

The theme
Custom module (developed by you)
Contrib module from Drupal.org

I can think of two approaches to go about and fix this.
Debugging
Replace the minified JS file(s) with non minified versions and start debugging.
Experiment
Try disabling modules/theme at turn until the problem disappears and try to pin point the part in the module/theme that causes the problem and from there try to find a solution.
Personally I would go for the experiment route, as this is often the fastest way to gain initial results.
Answer: The error comes from misc/jquery.js, and happens even when going through the installation procedure. So nope, it doesn't come from contrib, theme or custom module, but from core itself.
After looking further into things, it seems to be JQuery-specific. I replaced the jquery.js file with the most recent, minified version. Problem still arised. Then with the most recent development (so not minified) version. Problem still exist. Then did the same thing with jquery.form.js. Still no solution.
Now, though, if I look at the errors it gives me (only on pages with JS, like the modules page, or the progress bar during installation), I get explanations like this for the errors:
Jquery.js, ln. 2525:
anonymous function does not always return a value
return;

Jquery.js, ln. 443:
anonymous function does not always return a value
else return;

Jquery.js, ln. 444:
anonymous function does not always return a value
},

So the endless errors seem to come from Jquery itself. Not sure how to fix this (besides the obvious fixing every line it reports), but will look further into this.
Edit:
Ok, like any good IDE where you can turn off warnings and show only errors (which isn't to say you got to ignore warnings. They're there for a reason), you can turn them off in Firefox too.
In the URL bar, type in about:config. In the filter field, type in javascript. One of the options shown, should be something like javascript.options.strict. Set it to FALSE and you're done. The endless list of warnings is gone. Let's just hope the Jquery folks'll fix it someday.
Comment: Raf,  did you then have the same issue as me and this was your fix?
Answer: Turn off strict mode in your browser.


AngularJS data binding with passed parameter

Question: Form:
<form novalidate name="form" ng-submit="addArticle(newPost)">
    <textarea ng-model="newPost.content" required></textarea>
    <button type="submit" ng-disabled="form.$invalid">
</form>

Controller:
angular.module('app').controller('StreamDetailCtrl', function($scope) {
    $scope.newPost = {};

    $scope.addArticle = function(newPost) {
        // [Post stuff to server]

        // Clear form
        newPost = {};
    };
});

The problem here is that the form isn't cleared, there is no data binding going on. Obviously if I would do $scope.newPost = {}; inside the method it works fine, but I can't use that (the real code has this addArticle method inside a different service, so I need to pass the newPost to it).
How can I bind this newPost parameter so that changing it changes my form?
Answer: You can try either:

newPost.content = null, if you only want to clear this property
angular.copy({}, newPost) will clear everything inside newPost (if you want to clean all properties)


Properties of a sum over the root-of-unity expression of polynomials over a finite field

Question: Consider a bivariate polynomial over the finite field $\mathbb{Z}_n$ of the form:
$$f(x,y) = c\cdot xy + g(y)$$
where $c$ is some non-zero constant and $g$ is some univariate polynomial.
Let $\omega_n$ be a primitive  $n$th root-of-unity. Consider the function $h : \mathbb{Z_n} \to \mathbb{C}$:
$$h(x) = \sum_{y\in \mathbb{Z}_n} \omega_n^{f(x,y)}$$
I'm interested in when $h$ corresponds to a function over the same finite field, i.e. when the codomain of $h$ (up to a scalar) consists of $n$th roots-of-unity.
For example, take $f$ to be the polynomial $xy+y^2$ over $\mathbb{Z_5}$. This gives the following evaluations of $h(x)$:
$$h(0) = \omega_n^{0} + \omega_n^{1} + \omega_n^{4} + \omega_n^{4} + \omega_n^{1}$$
$$h(1) = \omega_n^{0} + \omega_n^{2} + \omega_n^{1} + \omega_n^{2} + \omega_n^{0}$$
$$h(2) = \omega_n^{0} + \omega_n^{3} + \omega_n^{3} + \omega_n^{0} + \omega_n^{4}$$
$$h(3) = \omega_n^{0} + \omega_n^{4} + \omega_n^{0} + \omega_n^{3} + \omega_n^{3}$$
$$h(4) = \omega_n^{0} + \omega_n^{0} + \omega_n^{2} + \omega_n^{1} + \omega_n^{2}$$
Note that $h(1) = h(4) = \omega_n^{1}\cdot h(0)$ and $h(2) = h(3) = \omega_n^{4}\cdot h(0)$. Therefore, taking the value of $h(0)$ as a scalar, $h(x)$ is equivalent to the function $x^2$ over $\mathbb{Z_5}$ (i.e. 0,1,4,4,1).
It seems that when $g$ is quadratic, $h$ corresponds to a quadratic function (over the finite field) as well (although not always identical as in the case above). Is this true? If so, what exactly is the relationship between $f$ and the function corresponding to $h$?
Similarly, it seems that when $g$ is cubic or above, $h$ does not correspond to a function over the finite field. Is this always true?
I'm sure there must be better terms to explain what I'm describing here - any pointers to relevant fields would also be helpful!
Comment: I'm struggling to find a good reference for this specific problem, but polynomial functions on $\mathbb{Z}/n\mathbb{Z}$ have been extensively studied, including characterizations of functions on $\mathbb{Z}/n\mathbb{Z}$ that can be expressed as various types of polynomials. Many elementary number theory books (*e.g.*, Borevich-Shafarevich) establish foundational results about solutions to polynomial congruences modulo $n$ and the values character sums using elementary methods. I'll post a reference if I remember one but just thought I'd help start the discussion here. `:)`
Comment: Thanks Dan! Are you aware of any particularly special properties of quadratic polynomials on finite fields (compared to those of higher degree)? I did find [this question](http://mathoverflow.net/questions/135949/a-question-on-maps-from-mathbbz-p-mathbbz-to-itself) which doesn't seem directly useful but certainly provided avenues to explore.
Comment: This is a kind of a discrete Fourier Transform of $g$ (or of $\omega^{g(y)}$ if you want to write it that way). The special restriction is that you want the components of the transform to have equal magnitudes and phases differing by a multiple of $2\pi/n$. Imma bit drunk now, but I think it will work for quadratics. May be Gauss' sums come to the fore (and there may be exceptions)? I'll come back to this after I catch some shut-eye (1am now).
Comment: Jyrki: That makes some sense so far; I look forward to your sober thoughts! For what it's worth, I do expect quadratics to "work" (i.e. map to quadratic functions). I'd mostly like to know how to prove that, and if it always fails for cubic and above (and if not, when does it work/fail?).
Answer: It works out as follows whenever $g$ is a quadratic polynomial and $n>2$, i.e. $n=p$ is an odd prime.
Let's write
$$
g(x)=a_2x^2+a_1x+a_0
$$
for some coefficients $a_0,a_1,a_2\in\Bbb{Z}_p,a_2\neq0$. All we need to do is to complete the square in the exponent. That is, let's rewrite
$$
cxy+g(y)=a_2y^2+(a_1+cx)y+a_0=a_2\left(y+\frac{a_1+cx}{2a_2}\right)^2+a_0-\frac{(a_1+cx)^2}{4a_2}.
$$
In the definition of $h$ the variable $x$ is a constant in the summation. Therefore we can as well use $t=y+(a_1+cx)/(2a_2)$ as the variable in the summation: when $y$ ranges over the field $\Bbb{Z}_p$ so does $t$. Therefore
$$
\begin{aligned}
h(x)&=\sum_{t\in\Bbb{F}_p}\omega^{a_2t^2+a_0-((a_1+cx)/(2a_2))^2}\\
&=\omega^{a_0-(a_1+cx)^2/(4a_2)}\sum_{t\in\Bbb{Z}_p}\omega^{a_2t^2}\\
&=\omega^{p(x)} S(a_2),
\end{aligned}
$$
where
$$
p(x)=-\frac{c^2}{4a_2}x^2-\frac{ca_1}{2a_2}x-\frac{a_1^2-4a_0a_2}{4a_2}\in\Bbb{Z}_p[x]
$$
is the quadratic function corresponding to $h$, and the constant (independent of $x$!)
$$
S(a_2)=\sum_{t\in\Bbb{Z}_p}\omega^{a_2t^2}
$$
is, indeed, a Gauss' sum.
The Gauss' sum is a complex number with absolute value equal to $\sqrt p$. When $a_2=1$, and $\omega=e^{2\pi i/p}$ it is known that $S(1)=\sqrt{p}$, if $p\equiv 1\pmod 4$, and $S(1)=i\sqrt{p}$, if $p\equiv-1\pmod4.$ See for example this Wikipedia article for some basic properties of Gauss' sums. A textbook would be better. Number theorists probably recommend Ireland & Rosen, books on Finite Fields such as Lidl & Niederreiter will also have this (and generalizations to other finite fields).
Comment: I think that there are some other special cases where this happens. I would use *bent function* as a keyword in a search engine. They applications in crypto and such. The first promising looking hit is [this](http://www.sciencedirect.com/science/article/pii/0097316585900494).
Comment: What probably happens when $g$ is cubic or higher is that the absolute values of $h(x)$ will (usually) depend on $x$. In the quadratic case they all have absolute value $\sqrt p$, and we can start looking at the variation of their phases.
Comment: Thanks Jyrki, that fits very nicely. I'll read up properly on Gauss sums. When you say "will (usually) depend on x", do you have any examples of it not doing so? (If it doesn't depend on x, will it necessarily be a Gauss sum?)


Formik onSubmit error: Can't perform a React state update on an unmounted component

Question: I get this error when trying to submit a Formik form.

Warning: Can't perform a React state update on an unmounted component.
  This is a no-op, but it indicates a memory leak in your application.
  To fix, cancel all subscriptions and asynchronous tasks in a useEffect
  cleanup function.
      in Formik (at layout.tsx:113)
      in div (created by ForwardRef(CardContent))
      in ForwardRef(CardContent) (created by WithStyles(ForwardRef(CardContent)))
      in WithStyles(ForwardRef(CardContent)) (created by Context.Consumer)
      in StyledComponent (created by Styled(WithStyles(ForwardRef(CardContent))))
      in Styled(WithStyles(ForwardRef(CardContent))) (created by CardContent)
      in CardContent (created by Context.Consumer)
      in StyledComponent (created by Styled(CardContent))
      in Styled(CardContent) (at layout.tsx:112)
      in div (created by ForwardRef(Paper))
      in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
      in WithStyles(ForwardRef(Paper)) (created by ForwardRef(Card))
      in ForwardRef(Card) (created by WithStyles(ForwardRef(Card)))
      in WithStyles(ForwardRef(Card)) (created by Context.Consumer)
      in StyledComponent (created by Styled(WithStyles(ForwardRef(Card))))
      in Styled(WithStyles(ForwardRef(Card))) (created by Card)
      in Card (at layout.tsx:111)

The function onSubmit has no async calls:
<Formik
  ...
  onSubmit={(values, { setSubmitting }): void => {
    setTimeout(() => {
      // convert daysOfWeek to Weekday[]
      const daysOfWeek = values.daysOfWeek
        .filter(day => day.checked)
        .map(day => day.dayOfWeek)
      const edited: EditTask = { ...task, ...values, daysOfWeek }
      onEditTask(edited)
      setSubmitting(false)
    })
  }}
>

The onEditTask callback just updates the list of TaskItems.
The full TaskItem component looks like this. The '@web/core...' components are my own wrappers around Material UI components.
TaskItem.tsx
import React, { ReactElement } from 'react'
import { useTranslation } from 'react-i18next'
import Grid from '@material-ui/core/Grid'
import ListItemIcon from '@material-ui/core/ListItemIcon'
import ListItemText from '@material-ui/core/ListItemText'
import CloseIcon from '@material-ui/icons/Close'
import Typography from '@web/core/components/Typography'
import MenuButton from '@web/core/components/MenuButton'
import MenuItem from '@web/core/components/MenuItem'
import TextField from '@web/core/components/TextField'
import Checkbox from '@web/core/components/Checkbox'
import Button from '@web/core/components/Button'
import Card from '@web/core/components/Card'
import EditIcon from '@web/core/theme/icons/Edit'
import { TaskSchedule, Weekday } from 'stores/goals/models'
import {
  EditTask,
  getDistinctTaskSchedulesSorted,
} from 'components/CitizenDetails/DietRules/FormDrawer'
import { TaskItemViewMode } from 'components/CitizenDetails/DietRules/TaskItem'
import { Formik, FieldArray, Form } from 'formik'
import uuid from 'uuid/v4'
import * as Yup from 'yup'
import TaskOverview from '../TaskOverview'
import { DeleteIcon, DeleteMenuItemText, EditCardContent, RemoveScheduleButton } from './styled'

const taskValidationSchema = Yup.object().shape({
  subject: Yup.string().required('Required'),
  description: Yup.string().nullable(),
  daysOfWeek: Yup.array()
    .min(1, 'Min 1 day')
    .required('Required'),
  taskSchedules: Yup.array()
    .ensure()
    .min(0, 'Min 0 elements'),
})

interface Props {
  viewMode: TaskItemViewMode
  task: EditTask
  onChangeViewMode: (viewMode: TaskItemViewMode) => void
  onDeleteTask: () => void
  onEditTask: (task: EditTask) => void
  disableMenu?: boolean
}

export interface CheckedWeekday {
  checked: boolean
  dayOfWeek: Weekday
}

function mapToCheckedWeekday(weekday: Weekday, checked: boolean): CheckedWeekday {
  return {
    dayOfWeek: weekday,
    checked,
  }
}

export default function TaskItem({
  viewMode,
  task,
  onChangeViewMode,
  onDeleteTask,
  onEditTask,
  disableMenu,
}: Props): ReactElement {
  const [t] = useTranslation()

  type TaskFormValues = Pick<EditTask, 'subject' | 'description'> & {
    daysOfWeek: CheckedWeekday[]
    taskSchedules: TaskSchedule[]
  }

  const initialValues: TaskFormValues = {
    ...task,
    daysOfWeek: Object.values(Weekday).map(day =>
      mapToCheckedWeekday(day, task.daysOfWeek.includes(day))
    ),
    taskSchedules: getDistinctTaskSchedulesSorted(task.taskSchedules),
  }

  return (
    <>
      {viewMode === TaskItemViewMode.View ? (
        <Grid container justify="space-between" alignItems="center">
          <Grid item>
            <TaskOverview task={task} />
          </Grid>
          <Grid item>
            {!disableMenu && (
              <MenuButton id="diet-task-overview-menu-button">
                <MenuItem onClick={(): void => onChangeViewMode(TaskItemViewMode.Edit)}>
                  <ListItemIcon>
                    <EditIcon />
                  </ListItemIcon>
                  <ListItemText primary={t('edit')} />
                </MenuItem>
                <MenuItem key="diet-task-overview-menu-remove-button" onClick={onDeleteTask}>
                  <ListItemIcon>
                    <DeleteIcon />
                  </ListItemIcon>
                  <DeleteMenuItemText primary={t('remove')} />
                </MenuItem>
              </MenuButton>
            )}
          </Grid>
        </Grid>
      ) : (
        <Card>
          <EditCardContent>
            <Formik
              initialValues={initialValues}
              validationSchema={taskValidationSchema}
              onSubmit={(values, { setSubmitting }): void => {
                setTimeout(() => {
                  // convert daysOfWeek to Weekday[]
                  const daysOfWeek = values.daysOfWeek
                    .filter(day => day.checked)
                    .map(day => day.dayOfWeek)
                  const edited: EditTask = { ...task, ...values, daysOfWeek }
                  onEditTask(edited)
                  setSubmitting(false)
                })
              }}
            >
              {({
                values,
                errors,
                isValid,
                touched,
                dirty,
                handleChange,
                handleBlur,
                handleSubmit,
                handleReset,
                isSubmitting,
                validateForm,
              }): ReactElement => (
                <Form>
                  <Grid container direction="column" spacing={3}>
                    <Grid item>
                      <Typography variant="h6">{t('goals:diet.task.title')}</Typography>
                    </Grid>
                    <Grid item>
                      <TextField
                        id={`task-${task.uuid}-subject`}
                        label={t('title')}
                        name="subject"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.subject}
                        fullWidth
                        inputProps={{ autoFocus: viewMode === TaskItemViewMode.Create }}
                      />
                      {errors.subject && touched.subject && errors.subject}
                    </Grid>
                    <Grid item>
                      <TextField
                        id={`task-${task.uuid}-description`}
                        label={t('description')}
                        name="description"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.description}
                        rows="3"
                        multiline
                        fullWidth
                      />
                    </Grid>
                    <Grid item>
                      <Typography variant="subtitle1" gutterBottom>
                        {t('day').toUpperCase()}
                      </Typography>
                      <FieldArray
                        name="daysOfWeek"
                        render={({ replace }) => (
                          <Grid container spacing={2}>
                            {values.daysOfWeek.map((day, idx) => (
                              <Grid item key={`task-weekday-${day.dayOfWeek}`}>
                                <Checkbox
                                  id={`task-weekday-checkbox-${day.dayOfWeek}`}
                                  name={`daysOfWeek.${idx}.dayOfWeek`}
                                  value={day.dayOfWeek}
                                  checked={day.checked}
                                  label={t(`weekdays.${day.dayOfWeek.toLowerCase()}`, {
                                    context: 'short',
                                  })}
                                  onChange={e => {
                                    replace(idx, { ...day, checked: !day.checked })
                                  }}
                                />
                              </Grid>
                            ))}
                          </Grid>
                        )}
                      />
                    </Grid>

                    <FieldArray
                      name="taskSchedules"
                      render={({ remove, replace, push }) => (
                        <>
                          <Grid item>
                            <Typography variant="subtitle1" gutterBottom>
                              {t('schedule_plural').toUpperCase()}
                            </Typography>

                            {values.taskSchedules.map((schedule, idx) => (
                              <Grid
                                container
                                spacing={6}
                                key={`task-weekday-schedule-${schedule.uuid}`}
                              >
                                <Grid item>
                                  <TextField
                                    type="time"
                                    key={`task-schedule-${schedule.uuid}`}
                                    id={`task-schedule-${schedule.uuid}`}
                                    label={t('time')}
                                    name={`taskSchedules.${idx}.time`}
                                    value={schedule.time}
                                    onChange={e => {
                                      const time = e.target.value
                                      replace(idx, { ...schedule, time })
                                    }}
                                    inputProps={{
                                      step: 300, // 5 min
                                    }}
                                  />
                                </Grid>
                                <Grid item>
                                  <RemoveScheduleButton
                                    id={`task-weekday-button-remove-schedule-${schedule.uuid}`}
                                    vanilla
                                    icon
                                    onClick={(): void => {
                                      remove(idx)
                                      // bug in formik makes this necessary
                                      // see https://github.com/jaredpalmer/formik/issues/784#issuecomment-503135849
                                      setTimeout(() => {
                                        validateForm()
                                      }, 10)
                                    }}
                                  >
                                    <CloseIcon />
                                  </RemoveScheduleButton>
                                </Grid>
                              </Grid>
                            ))}
                          </Grid>
                          <Grid item>
                            <Button
                              id="task-weekday-button-add-schedule"
                              ghost
                              onClick={(): void => {
                                push({
                                  time: '00:00:00',
                                  taskUuid: task.uuid,
                                  uuid: uuid(),
                                  dayOfWeek: Weekday.Monday, // temporary value
                                })
                              }}
                            >
                              {t('goals:diet.task.add-schedule')}
                            </Button>
                          </Grid>
                        </>
                      )}
                    />

                    <Grid item>
                      <Grid container justify="flex-end" spacing={2}>
                        <Grid item>
                          <Button
                            id="task-button-cancel-editing"
                            size="small"
                            ghost
                            licorice
                            onClick={
                              viewMode === TaskItemViewMode.Create
                                ? onDeleteTask
                                : (): void => {
                                    handleReset()
                                    onChangeViewMode(TaskItemViewMode.View)
                                  }
                            }
                          >
                            {t('cancel')}
                          </Button>
                        </Grid>
                        <Grid item>
                          <Button
                            type="submit"
                            id="task-button-save-editing"
                            size="small"
                            disabled={!dirty || !isValid || isSubmitting}
                          >
                            {t('ok')}
                          </Button>
                        </Grid>
                      </Grid>
                    </Grid>
                  </Grid>
                </Form>
              )}
            </Formik>
          </EditCardContent>
        </Card>
      )}
    </>
  )
}

Answer: Probably onEditTask is changing the viewMode, removing the <EditCardContent>, so when the call to setSubmitting happens Formik is already unmounted.


How $y^2 \over (1+y^2)$ can be simplified to $1 - \frac 1{(1 + y^2)}$?

Question: Basically, I am trying to solve a differential equation, and in my book there is this statement
"We can simplify $\frac{y^2}{1+y^2}$ to $1-
\frac{1}{1+y^2}$"
I want to know what are the underline steps that were taken to get this $1 - \frac{1}{1 + y^2}$.
Thanks.
Comment: $\frac{y^2}{1+y^2} = \frac{(1+y^2) - 1}{(1+y^2)}$ should be helpful, along with the fact that $\frac{a+c}{b} = \frac ab + \frac cb$. [This is the page you should visit](https://math.meta.stackexchange.com/questions/33179/short-and-helpful-advice-on-using-mathjax-on-the-site) if you wish to write your expressions more neatly and presentably.
Comment: this is a common 'trick' of adding zero. the authors added $0=1+(-1)$ in the numerator of the fraction and then simplified.  another common trick you may see is to multiply by one in the form of $1=a/a$ for some non-zero $a$, whatever it may be.
Comment: @TeresaLisbon: Can you post an answer or even the OP, can you? This makes sure the question *is answered*. Or I can, as you wish?
Comment: Thanks, guys this was helpful.
Comment: @nomantufail Ok, welcome!
Comment: @ultralegend5385 I think you can do so. I would have, but I don't know, I just feel it's too small! Please do so. I for one will take a look once you are done.
Answer: I am just posting what @TeresaLisbon said in the comment (of course with slight modifications in presentation and speech).
So, we have
$$\frac{y^2}{1+y^2}=\frac{y^2+{\color{blue} 1}-{\color{blue} 1}}{y^2+1}$$
Then, we can use the fact that subtraction is distributive over division, so we can "distribute" over. The expression becomes
$$\frac{y^2+1}{y^2+1}-\frac{1}{y^2+1}$$
The left term nicely cancels out and we get
$$\boxed{1-\frac{1}{y^2+1}}$$
Hope this helps. Have a good day :)


MySQL delete returning before complete in php

Question: Summary: It appears that my 'delete' statement returns before it is finished deleting. How can wait until it is done?
Long version: I have a PHP script running against an innoDB MySQL table that deletes a set of records from the database. Something like:
delete from sections where term = '15/FA'
I then follow up with a set of insert statements.
The problem is, my code will be partially into inserting my new records when the prior delete finishes and clears out some of the new records I inserted. That's bad.
If I call 'sleep()' for a second after calling the delete everything runs fine. Obviously that's not a proper or reliable solution, but it does show there is a timing issue.
There may be more, less, or different records than the records I just deleted. Using 'update' instead of insert isn't going to work.
I use the auto-increment id I get back from the insert to insert more records into a child tables. So it isn't practical to do the whole set of deletes and inserts in one long script. (Or if it is, I don't know how.)
So is there some way to know when the 'delete' function is done? Or do I need to give up and switch to a real database?
Comment: Did you try using a Transaction in MySQL?
Comment: post some code so we can actually help
Comment: Some code could be helpful
Answer: The DELETE will not return before deleting the rows.  Please describe, in detail, the steps that made you think that happened.
You have the InnoDB tag, so I assume you are using InnoDB?  Is more than one connection involved?  Is term indexed?  Are you using BEGIN...COMMIT?  Did a transaction get ROLLBACK'd?
If all of these occur, it could appear that something is amiss:

You have two separate connections -- one with the DELETE.
The transaction_isolation_mode is READ_UNCOMMITTED or something like that.
The second connection starts looking for the record before the DELETE is COMMITted.
You fail to check for errors.
Answer: This can happen when you have large number of rows in the table so the query does take a while. You could try adding an index on the column you want to filter in the delete query.
Comment: [It's not hard to earn enough rep to make comments.](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead)
Comment: @Jay Thanks. I will take care now onwards.


Modify a variable such as to get a particular correlation coefficient value with the other variable

Question: I am working on a problem where i have to change a column to make it 0.75 correlated to some other column.
suppose i have two columns X1 and X2.
The current Pearson correlation coefficient between them is 0.10.
I want to modify X2 in some way such that the coefficient coefficient between X1 and X2_mod = 0.75
Is their a statistical way to go about doing it, i just cant figure out one without generating a whole new column from scratch.
PS. i have to do it for several columns, i.e. X1, X2... X100
and the goal is to have corr(X1,X2_mod) = 0.75, corr(X1,X3_mod) = 0.75, corr(X1,X4_mod) = 0.75 ..... corr(X1,X100_mod) = 0.75
We can assume using the Pearson Correaltion Coefficient and each column has about 10000 data points.
Thanks in Advance
Comment: You can change the correlation by adding a multiple of the variable you're taking the correlation with. That is, $X_{2^*}=X_2+kX_1$ for some $k$.
You can derive a quadratic equation in $k$ that is a function the new and old correlation and the variances of $X_2$ and $X_1$.
Comment: Oh i will try this and see if it works, thanks
Answer: You can change the correlation by adding a multiple of the variable you're taking the correlation with. That is, $X_{2^*}=X_2+kX_1$ for some $k$.
You can derive a quadratic equation in $k$ that is a function the new and old correlation and the variances of $X_2$ and $X_1$.
\begin{eqnarray}
\text{Cor}(X_2+kX_1,X_1) &=& \text{Cov}(X_2+kX_1,X_1)/\sqrt{\text{Var}(X_2+kX_1)\text{Var}(X_1)}\\
  &=& \frac{[\text{Cov}(X_2,X_1)+k\text{Cov}(X_1,X_1)]}{\sqrt{[\text{Var}(X_2)+2k\text{Cov}(X_2,X_1)+k^2\text{Var}(X_1)]\text{Var}(X_1)}}\\
  &=& \frac{\rho\sigma_2\sigma_1+k\sigma_1^2}{\sqrt{[\sigma_2^2+2k\rho\sigma_2\sigma_1+k^2\sigma_1^2]\sigma_1^2}}
\end{eqnarray}
That is,
$$\rho^2_\text{new} [\sigma_2^2+2k\rho\sigma_2\sigma_1+k^2\sigma_1^2]\sigma_1^2 = (\rho\sigma_2\sigma_1+k\sigma_1^2)^2$$
This is a quadratic equation in $k$, so we can rearrange to get coefficients of $k^2$, $k$ and the constant, plug into the usual quadratic formula and then remove the spurious root that was introduced by squaring, leaving the required $k$.
Comment: Wow this worked, i worked out the math from your previous comment and it worked for me, and this equation checks out with what i got. Thanks a lot. :D


How to get compare variables of a list individually?

Question: So I have this code below that I'm trying to make, to where it will sort any list I give it so the lowest variable will be at the beginning, in position [0]. The problem I think is when the while loop comes in it compares uList[y] to the sum of uList[z:p] but, I was hoping it would compare it to each of the numbers individually so that if uList[y] is greater than ANY variable in uList[z:p] it would step into the loop how ever it does not. How would I go about making it compare the variables individually rather to the sum of them all, if that is whats happening.
Code:
import random
import sys
import os
import time
clear = lambda: os.system('cls')
clear()

y = 0
z = 1
x = 0
nNum = 1
uList = []
sList = []

listL = int(raw_input("How many elements would you like to be in your list?"))

clear()
while x < listL:
    uList.append(int(raw_input("Num %s:" %(nNum))))
    x = x + 1
    nNum = nNum + 1

p = len(uList) - 1

clear()
print("Your list was %s!" %(uList))

while z <= p:
    while uList[y] > uList[z]:
        j = uList[y]
        del uList[y]
        uList.append(j)

print(uList)

P.S. Any other tips or advice on anything about my code would be greatly appreciated as I am very obviously knew to python and coding in general lol, thank you so much!
Comment: What are you trying to do? Do you maybe want to sort the list?
Comment: I'm in trouble understanding your question. But you want to check if uList[y] is greater than the max of uList[z:p]?

if so the condition should be `uList[y] > max(uList[z:p])`

Edit : Pointed out in previous comment : you are trying to sort : if you want to sort, use built in function. If you wan't to do it with your own script, I let my comment.
Comment: Yes I want to sort but I want to write my own code to sort just for experience, and I want it to go into the while loop if uList[y] is greater than ANY  variable from uList[z:p], I think your code will work i would just have to change max to min. @T.Nel
Answer: The comments under your answer suggest that you have already solved your problem but because you asked for some Python advice: the 'pythonic' way to iterate is by using a for loop with a range instead of a while loop.
i = 0
while i < 10:
    i += 1

Becomes:
for i in range(10):
    pass

If you want to get the indices of the sequence you are iterating over you can use enumerate.
my_list = [*range(10)] # this is basically a for loop creating a list

for index, element in enumerate(my_list):
    print(index, element)

This gives you:
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

One last thing though. I am not sure if you are using Python 2 or 3 because you are using raw_input (Python 2) and print() (Python 2 or 3). If you are learning Python or programming in general I would recommend you go with Python 3 because it is easier to learn in some aspects and offers various improvements in efficiency and effectiveness.


PHP MySQL : Unable to Connect to Database

Question: i am trying to connect to database in php , Database name is photo_gallery following is my code
Database.php
    define("DB_SERVER", "localhost");
    define("SERVER_NAME", "root");
    define("DB_PASS" ,"");
    define("DB_NAME", "photo_gallery");

    class MySQLDatabase{

        function __construct(){
            $this->open_connection();
        }

        private $connection ;
        public function open_connection (){
        $this->connection = mysqli_connect(DB_SERVER, DB_NAME, DB_PASS);
            if(!$this->connection){
                die("Connection failed".mysqli_error());
        }
        else {
            $db_select=  mysqli_select_db($this->connection,DB_NAME);
            if(!$db_select){
                echo 'Database selection failed '.mysqli_error($this->connection);
            }
        }
    }
        public  function query($sql){
            $query = mysqli_query($this->connection,$sql);
            $this->confirm_query($query);
            return $query;
        }

        private function confirm_query($result_set){
            $query= mysqli_query($this->connection,$result_set);
            if(!$query){
                    die('Database query failed '.mysqli_error());
            }
        }

        public function close_connection(){
            if(isset($this->connection)){
                mysqli_close($this->connection);
                unset($this->connection);
            }
        }
    }

now when i run i get following error

Database selection failed Access denied for user: ' @' @ localhost ' .
  Base ' photo_gallery

i have confirmed username / password and db  details but still unable to resolve . Please guide me about it
Comment: `mysqli_connect` is missing an argument
Comment: Also, it apparently looks like you are using `DB_NAME` which might be the _database name_ rather than the username.  Isn't `SERVER_NAME` (root) your user here?
Comment: Look at the HTML page source with this error. I suspect you're missing some information, like `<>` characters in there.  In any case, it is clear that it's an access issue. The username connecting doesn't have access. But your username should not look like `user@localhost` as implied by the `@` there in the error. It should just be `user`
Comment: @dagon db name is optional. `mysqli_select_db()` is called later
Comment: i mis-typed not missing, just the wrong one
Comment: Are you writing your own ORM? That's probably not a good idea. Modern PHP development encourages the use of a [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/)  that gives you a solid foundation for building your application. Find one that suits your style and needs and follow the examples and documentation. Most have a large library of community code you can add in with little effort, avoiding the need to reinvent the wheel.
Comment: @tadman  i am learning how to develope oop based simple cms  from scratch ..
Comment: That's am ambitious undertaking. You might want to build it on top of a framework or you'll have one heck of a time getting it feature complete. Writing PHP from the ground up is extremely time consuming and unless you've worked with several frameworks before and know them inside and out, you'll probably spend a lot of time painfully repeating the mistakes of others. Your code here prevents people from using the placeholder feature, for example, rendering your code vulnerable to severe SQL injection bugs.
Answer: You haven't supplied a username - your mysqli_connect(DB_SERVER, DB_NAME, DB_PASS) line doesn't define a user, so you're trying to connect to your database with no user.
Try mysqli_connect(DB_SERVER, SERVER_NAME, DB_NAME, DB_PASS) instead.
Answer: second parameter of the connect method of mysqli-connect is the USERNAME .
use it like this
$this->connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASS, DB_NAME );
http://php.net/manual/en/mysqli.construct.php
Answer: Your problem is that you chose bad names for your constants..
SERVER_NAME is not a good name for the database username..
As a consecuence of this, you used it wrong.. I suggest to change the constant to DB_USER and use it properly in the mysqli_connect() function..
Remember to use names that really represent what they do/refer..
Answer: This is the syntax:
   $conn= mysqli_connect("myhost","myuser","mypassw","mydb");

Here is the code:
Database.php
    define("DB_SERVER", "localhost");
    define("SERVER_NAME", "root");
    define("DB_PASS" ,"");
    define("DB_NAME", "photo_gallery");

    class MySQLDatabase{

        function __construct(){
            $this->open_connection();
        }

        private $connection ;
        public function open_connection (){
        $this->connection = mysqli_connect(DB_SERVER, SERVER_NAME, DB_PASS, DB_NAME);
            if(!$this->connection){
                die("Connection failed".mysqli_error());
        }
        else {
            $db_select=  mysqli_select_db($this->connection,DB_NAME);
            if(!$db_select){
                echo 'Database selection failed '.mysqli_error($this->connection);
            }
        }
    }
        public  function query($sql){
            $query = mysqli_query($this->connection,$sql);
            $this->confirm_query($query);
            return $query;
        }

        private function confirm_query($result_set){
            $query= mysqli_query($this->connection,$result_set);
            if(!$query){
                    die('Database query failed '.mysqli_error());
            }
        }

        public function close_connection(){
            if(isset($this->connection)){
                mysqli_close($this->connection);
                unset($this->connection);
            }
        }
    }


proving orthogonality of associated Laguerre polynomial using Generating function

Question: I have been trying to prove the following orthogonal relation which is used for the normalization of the hydrogenic radial wave function,
$$\int_{0}^{\infty}e^{-\rho}\rho^{2l+2}[L^{2l+1}_{n+l}]^2d\rho=\frac{2n[(n+l)!]^{3}}{(n-l-1)!} \tag{1}$$
using the generating function
$$U_p(\rho,s)=\frac{(-s)^pe^{\frac{-\rho s}{1-s}}}{(1-s)^{p+1}}=\sum_{q=p}^{\infty}\frac{L^{p}_{q}(\rho)}{q!}s^{q} \tag{2}$$
plugging (2) into (1) and relabeling $k:=2l+1$ and $m:=n+l$ I get
$$\frac{(-1)^{2k}(st)^{k}}{[(1-s)(1-t)]^{k+1}}\int^{\infty}_{0}\rho^{k+1}e^{-\rho\frac{1-st}{(1-s)(1-t)}}d\rho=\sum_{v}^{\infty}\sum_{w}^{\infty}\frac{s^{v}}{v!}\frac{t^{w}}{w!}\int_{0}^{\infty}e^{-\rho}\rho^{k+1}L^{k}_vL^{k}_{w}d\rho \tag{3}$$
Now using integration by parts iteratively on the LHS of $(3)$ I get
$$\frac{(-1)^{2k}(st)^{k}}{[(1-s)(1-t)]^{k+1}}\frac{(-1)^{k+2} [(1-s)(1-t)]^{k+2}}{(1-st)^{k+2}}\Gamma[k+2]=\frac{(-1)^{k+2}(st)^{k}(1-s)(1-t)}{(1-st)^{k+2}}\Gamma[k+2] \tag{4}$$
I then used the binomial expansion of the denominator on the RHS of $(4)$.
$$ (1-st)^{-k-2}=\sum^{\infty}_{z=0}\binom{-k-2}{z}(-1)^z(st)^z \tag{5}$$
Looking at the binomial coefficient,
$$\binom{-k-2}{z} = \frac{(-k-2)(-k-2-1)...(-k-2-z+1)}{z!}=\frac{(-1)^{z}(k+z+1)!}{z!(k+1)!} \tag{6}$$
plugging $(6)$ and $(5)$ into $(4)$ and expanding the powers of $s$ and $t$  I get the following,
$$\begin{eqnarray}(4) &=& (-1)^{k+2} \Gamma[k+2] \sum^{\infty}_{z=0} \frac{(k+z+1)!}{z!(k+1)!} [-s^{k+1+z}t^{k+z}-s^{k+z}t^{k+1+z}+(st)^{k+z+1}+(st)^{k+z}] \\  &=& \sum_{v}^{\infty}\sum_{w}^{\infty}\frac{s^{v}}{v!}\frac{t^{w}}{w!}\int_{0}^{\infty}e^{-\rho}\rho^{k+1}L^{k}_vL^{k}_{w}d\rho\end{eqnarray} \tag{7}$$
Here is where I get stuck I don't really know where to go from here. Looking at the RHS of $(7)$ if $ v\neq w$ the integral is zero since Laguerre polynomials are orthogonal functions. Ive tried comparing coefficients of $st$ for example $k+z+1=2v$ since $v=n+l$ and $k=2l+1$ solving for $z$ I got $z=2n-2$ plugging that into the coefficient I got $\frac{n(n+l)!}{n!}$ which isn't right, there is also the issue of that $(-1)^{k+2}$ factor out front which I cant get rid of. Any help would be appreciated ive spent a long time trying to figure this out.
Answer: So I managed to figure it out and thought I would leave the answer for anyone elese who might be stuck as I was.
Firstly, I will address the factor $(-1)^{k+2}$ which is simply an my error when calculating the integral on the LHS of $(3)$. The integral actually gives
$$\int^{\infty}_0\rho^{k+1}e^{-\rho \frac{1-st}{(1-s)(1-t)} } d\rho = \frac{[(1-s)(1-t)]^{k+2}}{(1-st)^{k+2}}$$
Secondly, when looking at the sum on the LHS of $(7)$ and comparing the coefficients of s and t in particular for when they have the same coefficients there is actually two contributions one from $(st)^{k+z}$ and another from $(st)^{k+(z-1)+1}$.
So again comparing coefficients $k+z=v$ so that $v=v-k=(n+l)-(2l+1)=(n-l-1)$.and looking at the binomial coefficients for the two $st$ contributions (i.e. for $v$ and $v-1$) we get.
$$\frac{(k+z+1)!}{z!(k+1)!}+\frac{(k+z)!}{(z-1)!(k+1)!}$$
which when inserting $k=2l+1$ and $z=n-l-1$ we get.
$$(n+l+1)\frac{(n+l)!}{(n-l-1)!(2l+2)!}+(n-l-1)\frac{(n+l)!}{(n-l-1)!(2l+2)!}=2n\frac{(n+l)!}{(n-l-1)!(2l+2)!}$$
Finally, We end up with
$$2n\frac{(n+l)!}{(n-l-1)!(2l+2)!}\Gamma[k+2]= \frac{1}{[(n+l)!]^{2}}\int^{\infty}_{0}e^{-\rho}\rho^{k+1}[L_{v}^{k}]^{2} d\rho$$
Which simply cancelling the gamma function and rearranging some terms gives the final answer.
$$\int^{\infty}_{0}e^{-\rho}\rho^{k+1}[L_{v}^{k}]^{2} d\rho = 2n\frac{[(n+l)!]^{3}}{(n-l-1)!}$$


Alter AUTO_INCREMENT value by select result

Question: Basically what I want is a working-version of the following code:
ALTER TABLE table_name
AUTO_INCREMENT =
(
    SELECT
        `AUTO_INCREMENT`
    FROM
        INFORMATION_SCHEMA.TABLES
    WHERE
        TABLE_SCHEMA = 'database_name'
    AND TABLE_NAME = 'another_table_name'
);

The error:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AUTO_INCREMENT =

The reason:
According to MySQL Doc:

InnoDB uses the in-memory auto-increment counter as long as the server
  runs. When the server is stopped and restarted, InnoDB reinitializes
  the counter for each table for the first INSERT to the table, as
  described earlier.

This means that whenever I restart the server, my auto_increment values are set to the minimum possible.
I have a table called ticket and another one called ticket_backup. Both of them have a column id that is shared. Records inside the ticket table are available and can be claimed by customers. When they claim the ticket I insert the record inside ticket_backup and then I erase them from ticket table. As of today, I have 56 thousand tickets already claimed (inside ticket_backup) and 0 tickets available. If I restart the server now and don't perform the ALTER TABLE, the first ticket I make available will have id 1 which is an ID already taken by ticket_backup, thus causing me duplicate key error if I don't fix the auto-increment value. The reason for me to want this in a single query is to be able to easily perform the query on server startup.
Comment: There can be no earthly why you would want to do this.
Comment: There is no `SET` in the query. The MySQL syntax error messages contain the fragment of the query starting with the syntax error was detected. It says: "SET AUTO_INCREMENT = "
Comment: @Strawberry I'll be editing the main question to provide my reason.
Comment: @axiac I already fixed that, one of the answers below was about that, but that didn't fix the problem.
Comment: Isn't it easier to run the two queries separately and use the client code to put the value retrieved using `SELECT` into the `ALTER TABLE`?
Comment: @axiac I edited the question to reflect on why I'm trying to reach this goal. I wanted a single query so I could just automatically execute this script at server startup.
Comment: @strawberry I finished the edition including my reasoning.
Comment: Don't erase them. And certainly not for numbers as small and insignificant as 56,000. Instead see partitioning.
Comment: That said, one wonders why you didn't simply refer to the comments section of that page !?!?
Comment: @Strawberry I will take a deeper look at partitioning, but the reason to divide the tables wasn't about performance but rather make the reports easier to handle. The software works perfectly, this was my only known issue that wasn't expected. I didn't refer to that page comment section because their solution only covers triggers and Stackoverflow is a great place for developers to find fast solution.
Comment: Indeed, fixing the AI value only once at server start sounds better than running two queries in a trigger before every insert. I wonder if it's not possible to use a variable as a guard to avoid those selects run after the AI was fixed on the first insert.
Answer: Try this:
SELECT `AUTO_INCREMENT` INTO @AutoInc
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'database_name' AND TABLE_NAME = 'another_table_name';

SET @s:=CONCAT('ALTER TABLE `database_name`.`table_name` AUTO_INCREMENT=', @AutoInc);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Comment: You'll receive the bounty rep tomorrow. Thank you.
Answer: Just upon quick glance, the error says it all. Syntax is incorrect
The syntax should adhere to:
ALTER TABLE table_name AUTO_INCREMENT=<INTEGER_VALUE>;

So looking at your query, remove the word "SET"
ALTER TABLE table_name AUTO_INCREMENT =
(
    SELECT
        `AUTO_INCREMENT`
    FROM
        INFORMATION_SCHEMA.TABLES
    WHERE
        TABLE_SCHEMA = 'database_name'
    AND TABLE_NAME = 'another_table_name'
);

Comment: Although that does make sense and points out my lack of attention towards the proper way to use ALTER TABLE, your solution did not work. I guess for some reason I can't execute a DML statement inside a DDL statement. My code is a mere explanation to what I would hope to achieve.
Comment: Yeah looking at http://stackoverflow.com/questions/2741485/set-auto-increment-value-programmatically, looks like you'll have to do it via application code instead of SQL. Interesting :) So, maybe have a postinst script which does that?
Comment: This didn't work for me either but the answer from Saharsh did.
Answer: What about
ALTER TABLE table_name
SET AUTO_INCREMENT = (SELECT MAX(a.AUTO_INC_VAL) FROM database_name.table_name a) )

if you want the current increment value or
ALTER TABLE table_name
SET AUTO_INCREMENT = (SELECT MIN(a.AUTO_INC_VAL) FROM database_name.table_name a) )

if you want the same initial INCREMENT VALUE
Comment: Neither of those options worked. Both of them gives me the same error as my statement.


How to pass data from form without a form field? (PHP)

Question: I have a form for editing a users name and email.
So when it updates the name and email, it needs the username to identify which row it should update.
So i wanted to know if there is any element which is passed with the form but without showing the value or being editable in the input tag.
So i get the username from one script.
The edit user script gets the name and email from the database with the specified username.
Then it passes that new name and email with the username to another script which updates it.
Answer: I believe you are looking for
 <input type='hidden' name='username' value='theusername' />

hidden - can only be seen in the source of your HTML document
name - where it will be in the $_REQUEST/$_POST/$_GET ($_POST or $_GET depending on how you are submitting your form)  variable on submit
value - the username you want this form to relate to

PRO TIP: Have a way to tell who is trying to update users so you don't have unauthorized people updating your user information.  It would be very easy for someone to change the username in the form and try to update someone else.
Comment: thanks, that worked. And u mean to say that anyone can change the code while sending the form and change someone else's details. So can u tell me how to make it more secure?
Comment: @Arjun Bajaj: How do you currently identify/authenticate your users?  There are lots of ways to make web applications more secure.  The primary thing to keep in mind is to _never_ implicitly trust client input.  You'll want to make sure a user is authenticated before processing this request, and make sure (using whatever authorization mechanism you use, any roles or permissions system) that the user is authorized to perform this action.  That latter bit leans a lot toward business logic, whereas the former is purely authentication.
Comment: Here is a tutorial I found, should start to give you a general idea: http://www.knowledgesutra.com/forums/topic/7887-php-simple-login-tutorial/
Answer: You can use input type hidden
<input type="hidden" name = "username" value="<?php echo $username ?>">

Answer: use an:
 <input type="hidden" />

HIDDEN is a TYPE attribute value to the INPUT element for FORMs. It indicates a form field that does not appear visibly in the document and that the user does not interact with. It can be used to transmit state information about the client or server. Hidden fields often store a default value (e.g.via php), or have their value changed by a JavaScript.
more here
Answer: Use a hidden input tag:
<input type='hidden' name='username' value='theusername' />

Answer: You can use a hidden form field:
<input type="hidden" name="originalUsername" value="something" />

This won't render on the form in the browser and will likely be ignored and unnoticed by the user.
However, be aware that this is editable.  Do not rely on this as a security measure.  When the form is submitted, make sure that the user submitting the form (using whatever authentication and authorization mechanisms you have in place) is authorized to make this change before persisting it to the database.  Any form field being submitted can be edited.
Answer: As all the others stated you need a hidden input. It WILL be editable though, never trust it as you never trust any other data coming from outside.
But I'd like to add that it would be nicer not to use the username for identifying a row, add an ID column as a primary key instead to your database (possibly auto incremented), and use that in your form.
Something like
<input type="hidden" name="userid" value="<?=$userid?>" />

Answer: Arun, you can use GET to pass variables from one page to another page. Simply construct URLs as edituser.php?username=arun and so on. This is the only possible way to pass on variables or data, of course apart from cookies, to other pages w/out using form tags.
Second method is to use JavaScript to create a hidden form field and update it with username.
Third one is to simply add hidden input tags. But this and latter will require form tags.
A word of caution, filter user inputs, be JS, GET or hidden fields.
Answer: Use this if you want to use it safely:
<input type='hidden' name='username' value='<?php echo encode("Please Encode Me!","This is a key"); ?>' />

wich will result into:
<input type='hidden' name='username' value='p3e4e4241674d2r4m4i5o464a4f2p3k5c2' />

and in the modification script you will have to use:
<?php $username = decode("p3e4e4241674d2r4m4i5o464a4f2p3k5c2","This is a key"); ?>

Below you have the PHP functions for the ENCODE/DECODE:
<?php

function encode($string,$key) {
    $key = sha1($key);
    $strLen = strlen($string);
    $keyLen = strlen($key);
    for ($i = 0; $i < $strLen; $i++) {
        $ordStr = ord(substr($string,$i,1));
        if ($j == $keyLen) { $j = 0; }
        $ordKey = ord(substr($key,$j,1));
        $j++;
        $hash .= strrev(base_convert(dechex($ordStr + $ordKey),16,36));
    }
    return $hash;
}

function decode($string,$key) {
    $key = sha1($key);
    $strLen = strlen($string);
    $keyLen = strlen($key);
    for ($i = 0; $i < $strLen; $i+=2) {
        $ordStr = hexdec(base_convert(strrev(substr($string,$i,2)),36,16));
        if ($j == $keyLen) { $j = 0; }
        $ordKey = ord(substr($key,$j,1));
        $j++;
        $hash .= chr($ordStr - $ordKey);
    }
    return $hash;
}

?>


Batch file to count occurrences

Question: I have a plain text file like this:
...
... TYPE: alm01, ........
...
...
...
... TYPE: almBB, ........
...
...
... TYPE: out, ......
...
... TYPE: in, ......
... TYPE: almBB, ........
... TYPE: out, ......
... TYPE: out, ......

(ellipsis is stuff from the line)
so using a batch file or cmd command (using pipes if necessary) I would like to count and output the number of occurrences of each type, from the example above, I want to output:
alm01 1
almBB 2
out 3
in 1

How can I do this?
FIRST ATTEMPT: (Not working)
@echo off
setlocal enableextensions enabledelayedexpansion

rem Configuration
set "file=test.log"

rem Clean environment
for /f "tokens=1 delims==" %%v in ('set _type_ 2^>nul') do set "%%v="

rem Search required lines
for /f "tokens=*" %%l in ('findstr "TYPE:" "%file%"') do (

    rem Now we have the whole line

    set "t=%%l"

    rem Remove the prefix of the line
    set "t=%t:*TYPE: =%"
    set "t=%t:~1%"

    rem Remove the suffix of the line (from comma to end) and
    rem increment counter of type
    for /f "tokens=1 delims=," %%t in ('echo %t%') do set /a "_type_%%t+=1"
)

rem Enumerate find types and echo type and number of occurrences
rem The inner loop is to allow underscores inside type
for /f "tokens=1,* delims=_" %%a in ('set _type_ 2^>nul') do (
    for /f "tokens=1,2 delims==" %%v in ("%%a") do echo %%v %%w
)

rem Clean and exit
endlocal
exit /b

Comment: that would be easy in bash. MS-DOS mean the pre-Win32 system, or just command prompt (cmd.exe)?
Comment: Yes, the question from V-X is critical. Do you really mean MS-DOS batch? or are you using Windows batch? MS-DOS capabilities are more limited.
Comment: @dbenham I want to do this with a bat file and execute it from a windows command (cmd) prompt.
Answer: @echo off
    setlocal enableextensions disabledelayedexpansion

    rem Configuration
    set "file=plaintext.txt"

    rem Clean environment
    for /f "tokens=1 delims==" %%v in ('set _type_ 2^>nul') do set "%%v="

    rem Search required lines
    for /f "tokens=*" %%l in ('findstr "TYPE:" "%file%"') do (

        rem Now we have the whole line
        set "t=%%l"

        rem Can't handle it inside the for loop. Go out to do it
        call :handleType
    )

    rem Enumerate find types and echo type and number of occurrences
    rem The inner loop is to allow underscores inside type
    for /f "tokens=1,* delims=_" %%a in ('set _type_ 2^>nul') do (
        for /f "tokens=1,2 delims==" %%v in ("%%b") do echo %%v %%w
    )

    rem Clean and exit
    endlocal
    exit /b

:handleType
    rem Remove the prefix of the line
    set "t=%t:*TYPE: =%"
    rem Remove spaces (not needed as OP stated and giving problems)
    set "t=%t: =%"

    rem Remove the suffix of the line (from comma to end) and
    rem increment counter of type
    for /f "tokens=1 delims=," %%t in ("%t:"=%") do set /a "_type_%%~t+=1"

    goto :EOF

EDITED
The problem is real file contains some special characters (! at least) inside lines, and those characters are expanded because the delayed expansion enabled, generating the error indicated by the OP.
To handle it, delayed expansion needs to be off, but since we are reading the file inside a for loop, to get access to the changed value of the variables delayed expansion needs to be on, so, leave it off and move lines of code for type management to a subroutine outside the for loop.
Comment: I have just tested it and it is not working. It says operator missed. Removing the prefix of the line is not working. Also you have some mistakes in the scripting. See the one I have posted with mistakes corrected. Anyway, it is not working.
Comment: Sorry but it is not working, the same error: "Operator missed". Furthermore, i think you have some syntax mistakes: when Enumerating found types and echo type and number of occurrences, in the inner loop it should be %%a instead of %%b. Also when removing prefix of the line in the handleType, at the beginning of the line after performing the set, it keeps an whitespace that you should remove using for example, set "t=%t:~1%". Finally, last line goto :EOF, where is EOF tag in the script? thanks a lot.
Comment: @user304602: At what line the error happens? %%b is ok, outer for separates `_type_` (in `%%a`) from the rest of the line (in `%%b`) using `tokens=1,*` and inner for separates type (in `%%v`) from the count (in `%%w`). The white space (one whitespace) is included in prefix remove. If there are more spaces, adapt as needed. `:eof` is a "predefined" label availabel when extensions are enabled and means `End Of File`. See `goto /?` for an explanation.
Comment: @user304602: How are your "TYPE" values really? What values can it have?
Comment: Now it is working, sorry. Only one mistake in your script: In the handletype body, in the for loop, instead of ("%t:"=%") is ("%t: =%"). Please, correct it. Also could you explain me why in the inner loop to enumerate found type is %%b and not %%a? I do not understand.
Comment: @user304602 No, the quote is to avoid errors if the right part of the line contains quotes. It should be where it is. I've added a space removal line just before.
Comment: @user304602: All the types are stored in environment variables in the form `_type_typename=count`, and are retrieved using a `set` command  that shows lines in the indicated format. It is necessary to separate the first part of the line (`_type_`), so a `token=1,*` clause is used, two tokens indicated. It will split the line in `type` and `typename=count` tokens (delimiters removed), first token is placed inside the `for` variable (`%%a` in this case), and the next in the next alphabetical variable (`%%b`). Two tokens, two variables.
Comment: Hi, what if the %t has special characters?

Batch file to count occurrences


How can I write undecuplets (11-tuplets) and duovigenuplets (22-tuplets) on Noteflight?

Question: I found these undecuplets (11-tuplets) and duovigenuplets (22-tuplets) in Chopin's Nocturne in B-flat minor, Opus 9, Number 1:

I want to use such tuplets in my own music. How can I write them in Noteflight?
Answer: Noteflight doesn't offer anything more than septuplets. There are several requests for more in the Noteflight feedback forum.
A work-around would be to split the tuplet up. Probably almost nobody can accurately play 22 notes over a whole measure.
Comment: @Vighnesh A sextuplet and a quintuplet. The alternative is to buy a professional notation program.
Comment: Chopin can know to play 22 notes in a whole measure.
Comment: 11 is a prime number. 22 is divisible by 2, but if you try to put a dotted whole note in Noteflight and then add a duplet, Noteflight will show a message saying that it can be divided into 2 dotted half notes without a tuplet. 22 is divisible by 11 but 11 is a prime number.
Comment: @Vighnesh Two sextuplets and two quintuplets would give you 22.
Comment: How to get 11 notes in a whole measure?
Comment: All the notes in the large tuplet must be of equal value.
Comment: Noteflight should really add this feature. It is very important for Chopin. Even larger tuplets are in the Nocturne in C-sharp minor, op. posth. It should be called 'Custom Tuplet' and its icon should be a tuplet bracket with either '#' or 'n' in it.


How to list folders where superuser has permissions on Windows Server

Question: Is there a way on windows server to list the folders where an superuser has permissions like
c:list permissions "superuser" ?
I would expect following result
c:\dddd\sfsf\dfsf
d:\sdfsdf\dfsf\fsdfsf
Thanks.
Comment: Something like [CACLS.exe](http://ss64.com/nt/cacls.html) or [PERMS.exe](http://ss64.com/nt/perms.html)?
Answer: Ok I have found a way.
The magical tools is subinacl. It works well.


Handle tab correctly when counting location information in Lex?

Question: I have read the manual about how to track location information, but still have problem. It seems that Lex (2.5) counts both space and tab as one character, and that makes the error reporting with wrong column number. Currently, I have the editor to replace tab with spaces for the parser. But I wonder if there is a way to handle tab correctly in Lex itself.
Comment: How many spaces equal one tab? 2? 4? 8?  This is a personal preference.  You'd have to build a configurable option into your lex-generated program to account for this preference.  It doesn't seem to me that it's worth the trouble.
Comment: In my case, the tab should be equal to 4 spaces. I tried to modify [YY_USER_ACTION](http://oreilly.com/linux/excerpts/9780596155971/error-]reporting-recovery.html), but without any luck. The column number always wrong.
Answer: You could use unputc to perform dirty trickery with the input stream. When you match a tab use unputc to put four spaces in the input steam...
Manual extract:

unput(c) puts the character c back onto the input stream. It will be
  the next character scanned. The following action will take the current
  token and cause it to be rescanned enclosed in parentheses.
{
int i;
/* Copy yytext because unput() trashes yytext */
char *yycopy = strdup( yytext );
unput( ')' );
for ( i = yyleng - 1; i >= 0; --i )
    unput( yycopy[i] );
unput( '(' );
free( yycopy );
}

Note that since each unput() puts the given character back at the beginning of the input stream, pushing back strings must be done
  back-to-front.


Jira Rest API: End date format not able to recognise

Question: Below is the response for "/rest/greenhopper/1.0/integration/teamcalendars/sprint/list?jql=project=" Jira API. 'end' field value looks long value but when I convert it is very large. Can you please suggest what format it is and how to convert to actual date?
Sample response:
{
      "id": 57997,
      "start": "10012017080605",
      "end": "24012017080600",
      "name": "Sprint 1 * 1/10-1/24",
      "closed": true,
      "editable": false,
      "projects": [
        {
          "key": "",
          "name": ""
        }
      ],
      "viewBoardsUrl": "https://*/secure/GHGoToBoard.jspa?sprintId=57997"
    }
Answer: the format is 24-01-2017 08:06:00. So it is a datetime format.
Hope this helps.


Copy data data from one worksheet to another with a condition

Question: I'm working on a macro that helps me to copy data from one worksheet to another in Excel with some conditions. I tried the following code; it works, but I got an infinite loop and I was not able to make the condition correctly in the code (I have to copy only the lines with the drop down list displays (complete), actually it's filled with  3 options (complete/cancel/in process)
Sub copier()
Dim ws1 As Worksheet, ws2 As Worksheet, src As Range, dest As Range, i As Integer
Set ws1 = Worksheets("Workload - Charge de travail")
Set ws2 = Worksheets("Sheet1")

For i = 2 To ws1.UsedRange.Rows.Count
    Set src = ws1.Range("A2" & i & ":AG10" & i)
    Set dest = ws2.Range("A2" & i & ":AG10" & i)
    If Source.Cells(1, 4).Value = "complete" Then
         src.Copy Destination:=dest
         dest.Value = dest.Value
         Next i
    End If
End Sub

Comment: I think you have an extra "End if" in your post... Also, you have your "Next i" inside your if statement.
Comment: the extra end if it has been posted  by mistake , where i can put my condition
Answer: Here some changes to your code that might help.
Sub copier()
    Dim ws1 As Worksheet, ws2 As Worksheet, src As Range, dest As Range, i As Integer

    Set ws1 = Worksheets("Workload - Charge de travail")
    Set ws2 = Worksheets("Sheet1")

    For i = 2 To ws1.Range("A1").SpecialCells(xlLastCell).Row
            ' this is more reliable than the method you used (which relies ont eh workbook being saved)
            ' but there must be no gaps in column A.

        ' Your code would not work.  Think about whay happens as i increases!
        ' ws1.Range("A2" & i & ":AG10" & i)

        Set src  = ws1.Range("A" & i & ":AG" & i+10  )
        Set dest = ws2.Range("A" & i & ":AG" & i+10 )

         If Source.Cells(1, 4).Value = "complete" Then
             ' what is source?
             ' What is this trying to do!  I think you mean i+1 not 1.
             ' I think you mean src not source.  I'm not psychic.

           src.Copy Destination:=dest
           dest.Value = dest.Value
        End If
    Next i
End Sub

Comment: source its for my drop down list
Comment: So the code I wrote only does the copy if yu have selected "complete" in your drop down list.  You need to use a lot more words and give us more info if we are going to be able help you more.
Comment: @Riadh.  Sorry but his isn't a code writing service and I find your explainations hard to follow.  I won't be able to offer you any more help that that already given.  I hope I have helped you somewhat.


Cakephp - Connect to different database/host from inside an action

Question: In cakephp I want to be able connect to a different database from one action on the site. The action determines which database and host to connect to. Using cakephp 1.3.
Ive seen where you can change the db connection in beforeFilter for a controller, but I want to be able handle this from the action, because that is where I find the database and/or host, that I need to connect to.
I can write my own SQL inside there. I don't need to go through models. Just want to do a simple add/update SQL statement.
Answer: You can easily configure more than one database connection to use in your app.
In config/database.php, create another variable for your database configuration, in addition to the existing $default:
var $otherDatabase = array(
    'driver' => 'mysql',
    // more settings...
);

Then, in your model, set $this->useDbConfig = 'otherDatabase' or in your controller $this->MyModel->useDbConfig = 'otherDatabase'. Any subsequent find()s will use the configured database.
Comment: So, I should create a new model and have that action use that new model. What If that action wants to set a different connection, can I pass variables to that model inside the action. ie $this->NewModel->db = "";
Comment: Yes, of course, your model instance is part of your controller, so you can change its `$useDbConfig` from your action method. Updated the answer to include this.


Melodic Criticism - Exercise 3.16G, Laitz The Complete Musician 2nd Edition

Question: The question asks to find the weaknesses or problems (based on the general guidelines for melody writing presented in the preceding section) in the following melodic contour (tunes without rhythm or meter) written in D minor.

I am struggling to find any problem with this contour, and these are my comments in response to each of the guidelines:

The melody begins on the member of the tonic triad 1 and resolves with a 2-1 melodic cadence.
The range of the melody is a minor sixth, so a very comfortable range.
The melody moves primarily in steps and makes two skips that don't create any new problems (e.g. dissonant intervals).
There are no more than two repeats of a patterns or sequence (e.g. 1-2-3, 2-3-4, 3-4-5). The second half of the melody is a retrograde of the first half, but this is only one repeat and it's not an identical repeat, so I don't see a problem here.
There is only one melodic climax in the middle of the contour.

The wording of the question also asserts that there is such a weakness or problem.
Comment: **Don't use [SOLVED] in your titles.**  That's an old forum habit that doesn't apply here.     Instead, click on the checkmark next to the correct answer to mark your post as "solved."
Comment: What is the exact wording of the guidelines? It's possible that they mention something you're missing.
Answer:
the two skips use the same pitches: E G and G E
sequences: A Bb A G and E F E D and the inverted G F G A

Neither of those 'break the rules' as you stated them, but maybe the textbook author thinks too much of the same melodic material is used.

...it does not resolve in a 2-1 melodic cadence...

Unless I misunderstand, it does end with a 2-1 melodic cadence. It ends E D or re do.
Personally, I find exercises like this difficult. They aren't about if it's good music, you're just supposed to find rule violations.
Comment: Ah! I was thinking of the modern key signature of one B flat for D minor. But, you're right there was an older practice of using a 'dorian' key signature for minor keys.
Answer: I can only think of two possible weaknesses with this melody:

It is too stepwise. There are only two non-step intervals in this melody, and they're both thirds between the same two pitches! Laitz mentions that one "can move with occasional skips (of thirds, fourths and fifths) to add interest"; thus perhaps having only two skips make the entire melody less interesting.
The stretch B♭–A–G–E outlines a tritone. This is sometimes a restriction in strict counterpoint, but one of Laitz's own examples traverses a tritone, so I doubt this is the reason.

But more important, this example was removed from future editions of the textbook. This suggests that either some of the reviewers of the book or Laitz himself (or both) felt that this example was problematic.
In short, you're 100% correct to doubt the legitimacy of this question. Others have as well, so much so that it's now been removed!


Drupal 6 hook for field access

Question: I want to use my own code to determine if a user has edit access on certain fields.  hook_field_access for Drupal 7 looks right.  Is there a comparable hook for Drupal 6?
Answer: A hook with exactly the same name exists for CCK in Drupal 6, it just doesn't seem to be all that well documented.
It's invoked from the content_access() function and has the following signature:
function MYMODULE_field_access($op, $field, $account = NULL, $node = NULL) {

}

Drupal 6 hook for field access


Group sequence value in column mysql

Question: Table mytbl have two columns: col_1 & col_2. I wanted to group range of values in col_1 for single col_2 value.
Example:

col_1
col_2

1
3

2
1

3
3

4
3

5
2

7
3

8
3

9
3

10
1

I wanted to filter out the a range for col_2 = 3.
it shows hiphen(-) for the end value when there is no range.
Result:

start
end
col_2

1
-
3

3
4
3

7
9
3
Answer: This is a gaps and island problem. Here is an approach using the difference between row numbers to identify the groups:
select
    min(col_1) as start_col_1,
    case when max(col_1) <> min(col_1) then max(col_1) end as end_col_1,
    col2
from (
    select t.*,
        row_number() over(partition by col2 order by col_1) as rn
    from mytable t
) t
where col_2 = 3
group by col2, col_1 - rn
order by start_col1

This returns null rather than '-' when the islands is made of just one record (that is because the latter is not a valid number).
This works as long as col_1 increments without gaps. Else, we can generate our own sequence with another row_number():
select
    min(col_1) as start_col_1,
    case when max(col_1) <> min(col_1) then max(col_1) end as end_col_1,
    col2
from (
    select t.*,
        row_number() over(order by col_1) as rn1,
        row_number() over(partition by col2 order by col_1) as rn2
    from mytable t
) t
where col_2 = 3
group by col2, rn1 - rn2
order by start_col1

Comment: I'm testing it with a huge data. The second one works fine but I wanted to add another condition to my where clause (actually filter by date if it may help)

Group sequence value in column mysql