HTML multi select how to deselect all if select first item using jquery

Question: I have a multi select control look like below,
When user select "Any", I want to deselect all other selected values and select only "Any", means, if user select "Any", do not allow to select other values else allow to select other values.
How its possible through jQuery
Thanks...
Comment: a fiddle might be helpful
Comment: you should probably add your answer among the answers instead of part of the question, it's not prohibited... at the same time @AlexChar provided a very nice answer, nice and clean (and short)...
Answer: jQuery("#select").change(function() {
    if (jQuery("#select option:first").is(':selected')) {
        jQuery("#select").val("any");
    }
});

To the form below:
<select multiple id="select">
    <option value="any">Any</option>
    <option value="...">...</option>
    ...
</select>

Answer: I think you want something like this:

$("select").on("change", function () {
    var selOption = $("option:selected", this).val();
    if (selOption == "any") {
        $(this).attr("selected", false);
        $(this).val("any");
    }
});

<select name="select2" multiple="multiple">
    <option value="any">Any</option>
    <option value="12">twelve</option>
    <option value="13">thirette</option>
    <option value="14">fourteen</option>
    <option value="15">fifteen</option>
    <option value="16">sixteen</option>
    <option value="17">seventeen</option>
    <option value="18">eighteen</option>
    <option value="19">nineteen</option>
    <option value="20">twenty</option>
</select>
Answer: In most cases this should work
$('.my-select').val('any')

Where is 'any' is a value of Any option.

(function() {
  var mSelect;

  mSelect = $('select');

  mSelect.on('click', function(event) {
    var values, needReset;

    values = mSelect.val();
    needReset = event.target.value === 'any' ||
       (values.length > 1 && values.indexOf('any') !== -1);

    if (needReset) {
      mSelect.val('any');
    }
  });
}());

<select multiple>
  <option value="any">Any</option>
  <option value="divorced">Maried</option>
  <option value="unmarried">Unmarried</option>
</select>
Comment: this will just update the value of the class `my-select` to `any`, doesn't even remotely answer the question...


MoveFile function convert syntax / how to use MoveFile with variables to rename folders

Question: This part of my programm tries to rename all folders and subfolders. All other functionality is in another code, here I'm just renaming a single folder by providing a path.
Since rename doesnt seem to work for me I tried using MoveFile.
I understand that it requires an LPCTSTR value.. but the paths I am currently providing (casted from std::filesystem::directory_entry -> std::filesystem::path) -> LPCTSTR) aren't accepted.
I'm getting that I'm not casting it the right way and I probably have to provide it with an "L" in front of the variable, but I can't find nor figure out the syntax.

bool renameFolder(std::string confirmStr3, auto dirEntry, std::string& replacedStr, std::string& insertStr, int& foldername_replacements)
{
    std::string path_string = dirEntry.path().string();

    path_string = std::filesystem::path(path_string).filename().string();

    replace_all(path_string, replacedStr, insertStr);

    path_string = getFolderPath(std::filesystem::path(dirEntry).string()) + "\\" + path_string;

    if (std::filesystem::path(dirEntry) != std::filesystem::path(path_string))
        foldername_replacements++;

    //std::filesystem::rename(std::filesystem::path(dirEntry), std::filesystem::path(path_string));
    MoveFile(LPCTSTR(std::filesystem::path(dirEntry)), LPCTSTR(std::filesystem::path(path_string)));

}

Comment: [Why should I not upload images of code/data/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors-when-asking-a-question)
Comment: Have you read the [help] yet? Particularly [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask).
Comment: I didn't downvote you.
Comment: Ok I realized it was you again :D Yes, I did read it. I mark everything I feel.. I only forgot to include the code the right way.. Oh and yeah Ill ignore to not post the error messages.. thats just plain dumb imo.. It's a short question and errormessages are very important for people that don't own a biological interpreter in their body.
Answer: You can't type cast a std::filesystem::path object directly to a character pointer. That is exactly what the error message is telling you.
And you can't use the L prefix with variables, only with compile-time literals.
You need to call the path::c_str() method instead, eg:
MoveFileW(std::filesystem::path(dirEntry).c_str(), std::filesystem::path(path_string).c_str());

Or, call the path::(w)string() method, and then call c_str() on the returned std::(w)string object, eg:
MoveFileW(std::filesystem::path(dirEntry).wstring().c_str(), std::filesystem::path(path_string).wstring().c_str());

That being said, std::rename() is likely to be implemented on Windows using MoveFile/Ex() internally, so this is a possible XY Problem. std::rename() is the preferred solution, so you should focus your efforts on figuring out why it is not working for you.

UPDATE:
On a side note, the code you have shown makes repetitive use of temporary std::filesystem::path objects that are unnecessary.  Try simplifying the code, like this:
bool renameFolder(std::string confirmStr3, auto dirEntry, std::string& replacedStr, std::string& insertStr, int& foldername_replacements)
{
    auto dirEntryPath = dirEntry.path();
    auto file_name = dirEntryPath.filename().string();

    replace_all(file_name, replacedStr, insertStr);

    auto newDirEntryPath = dirEntryPath / file_name;
    if (dirEntryPath != newDirEntryPath)
    {
        ++foldername_replacements;

        //std::filesystem::rename(dirEntryPath, newDirEntryPath);
        MoveFileW(dirEntryPath.c_str(), newDirEntryPath.c_str());
    }
}

Comment: yeah i think i get you! thank you very much! :)
Comment: Hey, maybe you'll read this. Wanted to thank you again for making me aware of the possible XY Problem, better the overall concept of it! :D It fixed a design flaw and brought me further in my studies <3 @remy-lebeau
Comment: I will look into that! Thanks for the insight! :) Got the project ready and done by now. It just renames all files, folders and content in less than a second, but Optimisation especially in C++ is always very important, so thanks for that! If someone wants to copy it (though its prob bad code :D), you can find it here https://github.com/Gisbert12843/FindAndReplace.
Comment: Don't yet understand why, but that code as it is and even in versions I altered a bit just doesn't work.. Doesn't matter if MoveFile or MoveFileW is used too mhhh
It just won't rename the folder, but says it does :D

I'll update this if I figure it out.
Comment: Define "doesn't work" exactly. You need to be more specific. Is `rename()` returning an error code, or throwing an exception? Is `MoveFileEx()` returning false, and if so then what does `GetLastError()` return?
Comment: Didn't fully debug it tbh.. it's not returning any errors at compile or runtime.. it just won't rename the folder ^^ I would guess it has something to do with formatting the path.. we had like 36°C the last 3 days so I didn't have the nerves to work that much :S will do that later to learn from it though!
Comment: @Gisbert12843 it can't fail to rename and not report an error. The only way I could think of for it to report success but still not rename is if the folder/file is in use and the OS is waiting for that to be released before then renaming it. Unless your debugging is faulty and you are simply diagnosing it wrong.
Comment: What i meant is, that it doesn't throw an exception of any kind.. I didn't debug it fully yet ^^ It just doesn't rename the folders but just seems to skip it.. you don't have to do more on that :D you really helped me more than enough! thx a bunch!!


Array and Linked Structures

Question: I am taking java data structures and algorithms class in school, and I am totally
lost on Array and Linked Structures, and if someone could please tell me some
good links or tutorials that explains well...thanks
array operation:

traversing
resizing
replacing an element
replacing an element
inserting an element
deleting an element

linked structure characteristics:

SLNode
traversing
replacing an element
replacing an element
inserting an element
deleting an element
Comment: I dont have it , because it is sold out in bookstore, im waiting for it in mail, i ordered it on Amazon...
Comment: weird that you came here to ask people to do your homework :P
Answer: Arrays (VB and Java)
http://msdn.microsoft.com/en-us/library/office/aa164778(v=office.10).aspx
http://www.dummies.com/how-to/content/understanding-arrays-in-java.html
Linked Lists
http://www.eternallyconfuzzled.com/tuts/datastructures/jsw_tut_linklist.aspx
http://cslibrary.stanford.edu/103/LinkedListBasics.pdf
Hope it helps!
Answer: First of all get the big picute and understand the difference between those two.
As mentioned in java doc

"An array is a container object that holds a fixed number of values of
  a single type. The length of an array is established when the array is
  created. After creation, its length is fixed".

In simply it means when you declare an array it should you should give a size.
If you think about the linked data structues you'll see they don't have predefinde size. Its like a chain. You can link new nodes to any where on the chain.
Read this
For manipulation of those read flowing articles.

http://www.geeksforgeeks.org/archives/10245
http://www.roseindia.net/java/collection/array-operation-collections.shtml

There are many linked data structures, But first learn ArrayList it might easy for you

http://www.anyexample.com/programming/java/java_arraylist_example.xml
http://www.roseindia.net/java/beginners/array_list_demo.shtml

Array and Linked Structures


ios não recebe push notifications

Question: O problema é o seguinte, na minha app o servidor envia notifications para os utilizadores mas não sei porquê os dispositivos não estão a receber as notificações.
O que já testei:
Lado do servidor envia as notificações sem problemas(certificados activos e corretos) e tokenID correto e ativo no dispositivo.
Usei a aplicação APN Tester Free para testar o envio de notificações em Produção com o mesmo certificado e neste caso ele envia e os dispositivos recebem as notificações.
O que poderá estar de errado para não conseguir receber as notificações?
Comment: Quando tive problema com isso foi certificado, estava enviando o push com certificado de desenvolvimento para o app que ja estava publicado na loja, em produção. Se der coloca um treco do codigo que faz o envio, verifica a resposta do apns.
Comment: @NeuberOliveira, como verifico a resposta do apns?
Comment: No caso fiz em php com stream_socket_*, nao tenho codigo agora, mas se nao me engano é so ler a stream com fgets e companhia.
Comment: Estou a programar em C# e chamo uma biblioteca da Apple e o método que uso é o seguinte: NotificationPayload payload = new NotificationPayload(device,message); List payLoadsList = new List { payload };PushNotification pushNotification = new PushNotification(false, path, password); List result = pushNotification.SendToApple(payLoadsList);; ele deveria retornar o token e no entanto vem a zero
Comment: Se ta funcionando no APN Tester Free, acho que pode ser essa lib que voce ta usando, tenta com outra lib, ou talvez fazer uns testes "na mao", talvez ate com curl de para fazer
Comment: @NeuberOliveira, obrigado pea dica realmente estou a usar uma lib que é MoonAPNS que já é um pouco antiga, tenho que ir procurar versões mais recentes e que sejam compativeis com a framework 4.0 que a mais atual deles não é. Ou você tem alguma que possa fazer a vez desta lib?
Comment: Desculpa ai mas nao manjo nada de C#, mas acho que o caminho é testar mesmo outras libs.
Comment: @NeuberOliveira valeu, e não sabe indicar outras libs?
Comment: Ninguém me consegue ajudar nisso não?
Comment: eu nao trabalho com C# o maximo que poderia fazer é postar um codigo em PHP que usei
Comment: @NeuberOliveira, Pena, que não sei como descalçar este problema. Obrigado na mesma.
Answer: Tenta esse código em C#:
<code>public static void EnviarNotificacaoPush(string tokeDispositivo, string mensagem, string caminhoCertificado, string senhaCertificado)
{
    using (var certificado = new X509Certificate2(File.ReadAllBytes(caminhoCertificado), senhaCertificado))
    {
        var enderecoPushApple = certificado.FriendlyName.StartsWith("Apple Development") ? "gateway.sandbox.push.apple.com" : "gateway.push.apple.com";
        using (var clientTcp = new TcpClient(enderecoPushApple, 2195))
        {
            using (var sslStream = new SslStream(clientTcp.GetStream()))
            {
                sslStream.AuthenticateAsClient(enderecoPushApple, new X509Certificate2Collection(certificado), SslProtocols.Default, false);
                using (var memoryStream = new MemoryStream())
                {
                    using (var writer = new BinaryWriter(memoryStream))
                    {
                        var payload = JsonConvert.SerializeObject(new { aps = new { alert = mensagem } });
                        writer.Write(new byte[] { 0, 0, 32 }.Concat(HexToData(tokeDispositivo)).Concat(new byte[] { 0, (byte)payload.Length }).ToArray());
                        writer.Write(payload.ToCharArray());
                        writer.Flush();
                        sslStream.Write(memoryStream.ToArray());
                        sslStream.Flush();
                    }
                }
            }
        }
    }
}

private static byte[] HexToData(string hexString)
{
    if (hexString.Length % 2 == 1)
        hexString = '0' + hexString;
    var data = new byte[hexString.Length / 2];
    for (int i = 0; i < data.Length; i++)
        data[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
    return data;
}
</code>
Comment: Obrigado, ajudou muito :)
Comment: Por nada. Demorou mas chegou. *rs ;)

ios não recebe push notifications


Need help analysing song

Question: Newbie here and just stared analysing songs
I came across this tune that has the following chord progression
Dmaj7 Dmaj7 | Fmaj7 Fmaj7 | F#m F | D D
The song seems to resolve on an A but doesnt have an A played in it.
But my question is from a composition standpoint. How and why would the composer come up with a 4-b6-6-b6-4 progression
Thanks a lot
Here's the link of the song
Comment: Hi and welcome to the music stack exchange. Can you reference the song that you are examining? From the progression alone, it would seem that the song is still in D major... And if not, it would likely be in A natural minor otherwise so, "4-6-sharp 6-6-4"
Comment: Hey Tim. Have added the youtube link of the song. Thanks :)
Comment: That's coming over to me as in key Bb! Help!
Comment: well yeah its A# actually. i transposed that to an A. But if you were to listen to the verse, it seems to resolve to an A# but right after the F##m, theres an F# followed by a D#. And not an A#
Comment: The key of A# is a very rare key to play in. Bb is the far more commonly used name. It also obviates the need for double sharps (## or x).
Answer: Judging from the roots, this is in B flat major... The intro goes like this:
Bb - Gm - Gb

He starts singing on the turn around - like this (bass enters on the second time through):
Eb - Gb - Gm - Gb - Bb

Then the verse is:
Eb - Gb - Eb - Gb

Then back to the turn around:
Eb - Gb - Gm - Gb - Bb - Gm - Gb - Eb

Those are the chords as analysized up to about 1:30 of the track...
EDIT
So as a follow-up on the numbering for what I am calling the 'turn-around' - 4, flat 6, 6, flat 6, 1
Then he adds 6, flat 6, 4 to the end later on... It's "resolving" on the IV7 chord in those instances in order to create that big tension in the feeling of the tune...
Beautiful song overall as well...  :)
Comment: Thanks a lot :) . I think thats a Gm and not a G. Also for some reason, i think it ends back on an Eb and not a Bb. But my question was from a composition standpoint. How would we explain using the flat 6. I mean of course the composer is free to use whatever chord he/she pleases. But what effect does using flat 6s and 6s bring in. Would there be any known progressions that are similar.
Comment: You are prob right about the Gm since the 3rd would be Bb... I was going by the roots alone (as is the habit of a bassist doing a quick study ;) - I'll edit that bit. As far as the how and why a composer chooses a progression... it's usually in order to create a mood or a feeling and/or because the progression is "sexy" in some way... difficult to speculate (and may be off topic as too subjective?) - perhaps the composer talks about the reasoning in an interview somewhere... But, I'll let you and our friend Google talk that one out haha

Need help analysing song


Passing VBA execution to another workbook

Question: I though there would be many answers to this question, but didn't find any obvious one.
Is it possible to pass VBA execution to another workbook ?
What I'd like to do is : pass execution from ThisWorbook (WbA) to another workbook (WbB, ie make WbB the new ThisWorkook), then close Wb A.
Edit
What I'm actually trying to do...
I'm looking for a way to update a workbook I'm distributing to a few people and which contains 20 sheets + 10 code modules + 10 userforms.
My current solution
Every time the workbook (WbA) is open, the code will first check if a newer version is available on a network directory. If so, the macro propose to the user to automatically download/save the new workbook (WbB) and export user data from WbA.
But, after that, I'm forced to tell the user it can now closed WbA and open WbB and import the data back in WbB.
I'd rather automate the close WbA / open WbB / import data back too.
Comment: The best idea is, as @Mat'sMug says, to use an add-in for the macros (and probably load those macros all the time), but I would keep the data in a separate workbook/s and only open it/them when it/they need to be used.  (i.e. the `xlam` should only contain the code and, perhaps, sheets containing lookup tables used to simplify coding - but any data, or anything the user can change / configure, would be in the data workbooks.)  And if the macros are updated to handle a new format of the data workbook, include code that automatically updates old format workbooks.
Comment: If you close the Workbook that originated the code call the code itself will close. AFAIK there is no way to pass execution to another workbook and then be able to close the originating workbook.
Comment: "...tell the user it can now close WbA and open WB and import the data back." - do you mean import the data back to WbA? ...Hm, what if you instead ran this from Personal.xlsb and went from there? Instead of storing this in WbA.  Or am I correct in Assuming you can't simply add this to people's Personal.xlsbs.  ...maybe run it from an Add-on?
Comment: @BruceWayne that. This is an application-level problem in need of an application-level solution. A nicely written Excel add-in could handle this much better.
Comment: Yes, call the second macro and pass the workbook(s) through to that macro, then you should be able to "reset" the variables and go from there.
Comment: I'm not sure if I completely understand your question, but you could put the VBA you are running in your personal macro workbook.  Then you can run it without the code being dependent on a specific workbook.
Comment: @ScottHoltzman - Ah yeah, I was just starting to write a way to do what I meant, and realized that when I close the workbook with the macro, of course the macro stops! :P
Comment: Perhaps this is an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). *Why* do you want to close the workbook and continue the same macro? Couldn't you write the first half of the macro, then call a second macro that picks up after the first?  Or, just hide the first workbook until the single macro is done, and *then* close it?
Comment: @ScottHoltzman - That what I though (pass execution is not possible). But I was surprised not to find such a question here.
Comment: @BruceWayne - I updated the question to add what I'm trying to do. Hiding such a big workbook is not an option and would left me with the same problem next time.
Comment: @BruceWayne - No, opening WbB then importing user data in WbB. - I'm not willing to use Personal.xlsb (and putting it in XLSTART...) since I don't want this big Wb to load everytime a user launch Excel (but only when needed) and since I'm not willing to modify user's Personal.xlsb. And regarding my problem of updating the macro, having it in XLSTART would probably make it more difficult. Regarding Add-On, I don't know much about that but wouldn't updating the Add-On be complicated too ?
Comment: You write it so that it *doesn't* need to be updated to handle a new version of WbA/WbB.
Comment: I should clearly separate `code` vs `user data & parameters` (and make it a real VB application). Actually, the macro do uses a `parameters folder` (C:/Temp/myMacro since it doesn't need any folder permission), for debug logging, error logging, temporary user data, downloads... It also make use of a read only `network folder` for updating lookup tables and databases... Having the code in a `xlam Add-In` would make sense considering the `application-level` vs `Wb-level` discussion, but if the `Add-In` contains all the code, wouldn't that make it more difficult to update the code and userfoms ?
Answer: You can do this by using Application.OnTime:
Code in WbA.xlsm:
Sub Macro1()
    Application.OnTime Now(), "WbB.xlsm!Macro2"
    ThisWorkbook.Close
End Sub

Code in WbB.xlsm:
Sub Macro2()
    MsgBox ThisWorkbook.Name & " says hello"
End Sub

Because Macro2 is being called by the Application via a scheduled task, it no longer needs WbA to be open.

Note:  WbB.xlsm does not even need to be open when Macro1 is run, providing you fully qualify the workbook name:
Code in WbA.xlsm:
Sub Macro1()
    Application.OnTime Now(), "'C:\Temp\SO_Test\WbB.xlsm'!Macro2"
    ThisWorkbook.Close
End Sub

Code in WbB.xlsm:
Sub Macro2()
    MsgBox ThisWorkbook.Name & " says hello"
End Sub

Assuming WbA.xlsm was the only workbook open in Excel when Macro1 was run, you might actually see an empty Excel for a very short time before WbB.xlsm is opened and execution continues.
Comment: Ok, I'm forced to upvote this. But I **have** to say this kind of circular-referencing code is completely disgusting and I would be **very** mad at whoever used this trick in production code. That hack defies the VBA call stack logic, defies common sense, defies everything that's good in the world.
Comment: @Mat'sMug You should know by now that I have no logic (even if VBA does have call stack logic), that I have no common sense, and that I (and everything else in the world) can't be called "good". :D
Comment: ...Wow, this is neat/crazy.  And also, I think I [found a picture of you](https://i.imgur.com/2Qgxpp4.png) writing this answer.
Comment: @BruceWayne People in my office are going to wonder what I am laughing about.  They might actually work out that I'm not doing what I am being paid to do - so stop posting those pics! :D
Comment: @Tibo Ah, I see now. You see a macro is meant to operate at workbook level, and IMO the problem you're solving is at application level - I'll try to spare a minute to write up a more idiomatic solution tonight.
Comment: @OP FWIW the *real* reason I dislike this solution is because `WbB.xlsm` has no business knowing about `WbA.xlsm` - the Golden Rule is that the object that creates something, is responsible for destroying that thing. So if A creates B, then B can't destroy A - it's A's responsibility to destroy B, by any programming standards.
Comment: @Mat'sMug - Edited answer so that `WbB.xlsm` knows nothing about `WbA.xlsm`.  (It's actually how I originally tested it, but I decided to move the close into `WbB.xlsm` just to ensure that it worked there too, and that's how it was when I pasted the code into the answer.)
Comment: That's **much** better!
Comment: @Mat'sMug Simplified it even more.  (I wasn't sure whether `OnTime` would handle a call to another workbook, but it does.)
Comment: I had a self updating sheet a while ago, upon open it would look for an open workbook with the same name and _old at the end and close it without save (this is incase it had just self updated). Then it would check for a new version, if it existed then it would rename itself to have _old at the end which didn't stop any code running, it would then copy the new one then the last thing the auto_open macro did was open the new one.
Comment: @YowE3K - Forget to mention I'd also need to pass some args to WbB (the location (WbC) of user data exported from WbA that need to be imported back in WbB). I don't think OnTime would let me do that (but I could export the location into some config file or stored those data in a know location)
Comment: @Mat'sMug - About to golden rule. Actually, next step would actually be WbB killing (ie destroying) WbA since WbB would become the new WbA (if that make any sense, see my edit about what I'm trying to do)
Comment: @Mat'sMug. This should totally be an application rather than a wb. We actually asked our external dev team if they could include an equivalent of my 'macro' in our Information System, but due to time constraint (+ an expected life time of the 'macro' of less than 10 months), I'm stuck with do what I can with Excel. I'm not sure of what an "idiomatic solution" means and looks like. Please, let me understand what that means before writing any code. (Another constraint is I need to be able to understand/update... the whole solution).
Comment: @Tibo very simple: make it an Excel add-in; it loads with Excel, and closes with Excel. I have ideas about how to deal with the versioning so that you don't need to redeploy the add-in every time a new version is issued, but essentially, move the app-level code to its own workbook and then Save As "Excel Add-in" - and then you can have fancypants buttons in the Ribbon to run your add-in code.
Comment: @Mat'sMug. The macro being rather big (20 sheets + 10 code modules + 10 userforms), I don't it to be launched with Excel but only when the user need it. To do so, maybe I could include in the Add-In only the fraction of the code needed to check if a new version of the macro in available on the network... But then I'm stuck with how to update the Add-In. (One reason to deploy the update could be that the network directory is expected to change in the next few days). I do use a personal xlam Add-In and Ribbon but I'm not sure if Add-In is easy to deal with when distributing it...
Comment: Huh, I used to run and distribute an Excel add-in with over 70 class modules. Not sure what the problem is here.
Comment: The Wb take about 6Mo, have about 150 Public Const, load big 2D arrays in memory, have 20 sheets with formatting... so I'd rather not have it loaded unless when necessary. (Note there aren't any class module since I have know idea about what it is used for...)
Answer: You just have to leave workbook A open while the code runs, the last line of code you need to execute should be
WorkbookA.Close

Comment: That doesn't fit my problem. I'm trying to pass execution and kill WbA, not just halt execution for a while...


Update.php: Page not found

Question: Currently using D7 (specifically the Commerce Kickstart installation profile). When trying to reach update.php, I get a "Page Not Found" error. I also noticed that the url Drupal is trying to reach is /core/update.php.
Has anyone else encountered this?
Answer: Do you have the .htaccess file from 8.x instead of the one from 7.x?
The directory structure of Drupal core changed from 7.x to 8.x, and 8.x includes additional mod_rewrite rules to redirect to the changed locations of update.php and install.php
Answer: This type of redirect to /core/ is likely to originate from a .htaccess file from Backdrop or Drupal 8+. The problem can occur even when using the .htaccess file from Drupal 7, if the browser has previously seen a Backdrop or D8+ site running at the same URL.
Those .htaccess files use a 301 Redirect (permanent redirect) which is remembered by the web browser. In this case it's necessary to clear (or temporarily disable) the cache in the browser, and then try the request again.

Update.php: Page not found


find limit by rationalizing?

Question: I'm extremely new to calculus so please excuse my lack of lingo/formatting.!
Here is the problem:
$$\lim_{n\to\infty} \sqrt{5n^2 + 4n +2} - \sqrt{5n^2 - 2n - 1}$$
Answer: To rationalize:

Multiply by $$\frac{\sqrt{5n^2 + 4n +2} + \sqrt{5n^2 - 2n -
   1}}{\sqrt{5n^2 + 4n +2} + \sqrt{5n^2 - 2n - 1}}$$
$$\left(\sqrt{5n^2 + 4n +2} - \sqrt{5n^2 - 2n -
   1}\right)\cdot\frac{\sqrt{5n^2 + 4n +2} + \sqrt{5n^2 - 2n -
   1}}{\sqrt{5n^2 + 4n +2} + \sqrt{5n^2 - 2n - 1}}$$ $$= \frac{6n+3}{\sqrt{5n^2 + 4n +2} + \sqrt{5n^2 - 2n - 1}}$$
Now, divide numerator and denominator by $n$.

You should end up with a limit $$\frac{6}{2\sqrt 5} = \frac 3{\sqrt 5} = \frac {3\sqrt 5}{5}$$
Comment: I've done relationalization, but can't go any step forward this
Comment: Write $n = \sqrt{n^2}$ when you divide the denominator by $n$, and then you can move the term inside the radicals.
Comment: You're welcome, linna!
Answer: Rationalizing expresion(multypling  nominator and denominator with ${ \sqrt{5n^2 + 4n +2} +\sqrt{5n^2 - 2n - 1}}$) you have $\lim_n\frac{6n+3}{ \sqrt{5n^2 + 4n +2} +\sqrt{5n^2 - 2n - 1}}$
And you have (dividing nominator and deonominator with n) that limit is 6/($\sqrt{5}+\sqrt{5}$) and that is 3/$\sqrt{5}$.
Comment: Your denominator converges to $2 \sqrt{5}$, not $10$.
Comment: I saw after I had typed. Thanks :)
Answer: Set $\dfrac1n=h\implies h\to0^+$  as $n\to\infty$
$5n^2+4n+2=\dfrac{5+4h+2h^2}{h^2}$
$\sqrt{5n^2+4n+2}=\dfrac{\sqrt{5+4h+2h^2}}{\sqrt{h^2}}=\dfrac{\sqrt{5+4h+2h^2}}{+h}$ as $h>0$
So, we have $$\lim_{h\to0^+}\dfrac{\sqrt{5+4h+h^2}-\sqrt{5-2h-h^2}}h$$
$$=\lim_{h\to0^+}\dfrac{(5+4h+h^2)-(5-2h-h^2)}h\cdot\dfrac1{\lim_{h\to0^+}(\sqrt{5+4h+h^2}+\sqrt{5-2h-h^2})}$$
Hope the rest can be handled easily

find limit by rationalizing?


Questão interessante sobre herança e polimorfismo

Question: Achei interessante esta questão de um concurso público:
Classe A
public class ClasseA {

 public int metodoX(){
   return 10
 }
 public int metodoX(int n){
   return metodoX() + n
 }
}

Classe B
public class ClasseB extends ClasseA{

  public int metodoX(){
    return 100
  }
  public int metodoX(int n){
    return metodoX() * n
  }
  public int metodoX(int m, int n){
    return metodoX(m) + metodoX()
  }
}

Principal
public class Principal {
  public static void main(String[] args) {
    ClasseA obj1 = new ClasseA()
    ClasseA obj2 = new ClasseB()
    ClasseB obj3 = new ClasseB()
    int r = obj1.metodoX() + obj2.metodoX() + obj2.metodoX(5) +
    obj3.metodoX(10, 100);
    System.out.println(r)
    }
 }

O resultado apresentado foi 1710. Confesso que fiquei confuso e gostaria que algum colega me explicasse com detalhes o desenvolvimento deste algoritmo.
Comment: Se poderia explicar aonde foi a confusão!
Comment: @DenisCaixeta Lembre-se que `ClasseB` herda de `ClasseA`, então uma variável do tipo `ClasseA` pode guardar um objeto do tipo `ClasseB`. Os métodos que podem ser chamados são os do tipo da variável (`ClasseA`), mas os métodos que são de fato chamados são os do objeto nela guardado (`ClasseB`). Ou seja, `obj2.metodoX(1, 2)` é erro de compilação, mas `obj2.metodoX()` chama o método `metodoX()` da `ClasseB`.
Comment: Você que esqueceu de colocar a maioria dos ponto-e-vírgulas ou foi o pessoal que fez o concurso que os essqueceu?
Comment: @VictorStafusa Estava assim, só copiei o colei.
Comment: Hahaha, então a resposta correta seria "*erro de compilação*" e você poderia entrar com um recurso para anular a questão. Se você considerar que os ponto-e-vírgulas faltantes seriam adicionados, aí sim daria 1710 e as respostas abaixo já explicam o porquê.
Comment: @VirgilioNovic  O instanciamento "ClasseA obj2 = new ClasseB()", porque será que fizeram assim?
Comment: Ok, entendi. Obrigado.
Comment: @DenisCaixeta nesse caso em especifico `ClasseA` na instância da variável `obj2` é o **tipo**, mas, sua instância é da `ClasseB` que herdou o comportamento da `ClasseA`, apesar que nesse o comportamento esperado é da `ClasseB` porque reescreveu os métodos `metodoX()` e `metodoX(int n)`. O método contido na ClasseB: `metodoX(int m, int n)` não faz parte do tipo da `ClasseA`, por isso nem aparece. É um boa pergunta muitos que trabalham com **POO** não sabe disso, e foi muito legal postar sua duvida, parabéns.
Answer: A explicação é o seguinte:
Existe um conceito na programação chamado de Sobrecarga de métodos, onde você cria métodos com o mesmo nome, porém com assinaturas diferentes. Variando o número de parâmetros e ou tipo de parâmetros.
Note os métodos da ClasseA, são métodos com o mesmo nome metodoX porém com parâmetros diferentes. Um não recebe parâmetros metodoX() e o outro recebe parâmetro do tipo int metodoX(int n).
public class ClasseA {

 public int metodoX(){ //assinatura sem parâmetros
   return 10
 }
 public int metodoX(int n){ //assinatura com parâmetro tipo int
   return metodoX() + n
 }
}

Agora vamos explicar o resultado:
int r = obj1.metodoX() + obj2.metodoX() + obj2.metodoX(5) + obj3.metodoX(10, 100);
int r = 10 + 100 + (100 * 5) + ((100 * 10) + 100);
int r = 110 + 500 + 1100;
int r = 1710

Veja a implementação das classes com comentários.
public class ClasseA {

 public int metodoX(){
   return 10
 }
 public int metodoX(int n){
   // return 10 + n
   return metodoX() + n
 }
}

public class ClasseB extends ClasseA{

  public int metodoX(){
    return 100
  }
  public int metodoX(int n){
    // return 100 * n
    return metodoX() * n
  }
  public int metodoX(int m, int n){
    // return (100 * m) + 100
    return metodoX(m) + metodoX()
  }
}

Agora se sobrecarga de métodos é um tipo de polimorfismo é outra conversa.
http://www.guj.com.br/t/sobrecarga-e-um-exemplo-de-polimorfismo/37028
Esse link tem uma discussão bacana a respeito.
Answer: Para entender o resultado é preciso desmembrar o cálculo abaixo em quatro partes.
int r = obj1.metodoX() + obj2.metodoX() + obj2.metodoX(5) +
obj3.metodoX(10, 100);

1ª Parte: obj1.metodoX()
O obj1 corresponde à classe ClasseA. A execução do metodoX() retorna o valor 10.
2ª Parte: obj2.metodoX()
O obj2 corresponde à ClasseB. Apesar do obj2 herdar os métodos da ClasseA, a execução do metodoX() é o da ClasseB, de modo que o valor retornado é 100.
3ª Parte: obj2.metodoX(5)
Esta chamada executa o metodoX(int n) da ClasseB, que por sua vez retorna o resultado da expressão metodoX() + n. O metodoX() chamado nessa expressão é o da ClasseB, que retorna o valor 100, ou seja, o resultado desta execução é 100 * 5 que é 500.
4 ª Parte: obj3.metodoX(10, 100)
Na chamada acima é executado outro método da ClasseB que faz chamadas aos métodos da própria ClasseB, retornando o valor 1100.
Dessa forma, o resultado final é 10 + 100 + 500 + 1100 = 1710.
Sobre a questão da herança, note que existem métodos da ClasseA com o mesmo nome na ClasseB.
Neste exemplo encontrado por você, a ClasseB herda os métodos da ClasseA, porém os métodos da ClasseA não foram utilizados na classeB. Por esta razão, todas as chamadas na ClasseB fazem referência aos próprios métodos e não aos da classe pai.
Para que, na classeB fosse realizada uma chamada a um método "metodoX()" da ClasseA, a chamada deveria ser precedida do ponteiro super.
Um breve exemplo seria:
public classe ClasseB extends ClasseA {
   public int metodoX(){
      return 100
   }

   public int metodoX(int n){
      return super.metodoX() * n
   }

   public int metodoX(int m, int n){
      return super.metodoX(m) + metodoX()
   }
}

Com o exemplo acima, a herança seria efetivamente utilizada no código, de modo que o resultado final seria diferente.
Com relação à sobrecarga, esta foi utilizada quando as classes foram implementadas com métodos de mesmo nome, porém com assinaturas diferentes.
Comment: A dúvida estava mesmo sobre a  herança, o exemplo que deu é muito bom.
Answer: Pelo que entendi a operação em r é:
int r = 10 + 100 + 500 + 1100;

por que:
O "obj1.metodoX()" é o primeiro método da classe a, onde retorna 10;
O "obj2.metodoX()" é o primeiro método da classe b, onde retorna 100;
Já o "obj2.metodoX(5)" é o segundo método da classe b, onde é pego o argumento n=5, vezes o primeiro método da classe b que retorna 100, isso da 500;
Por ultimo "obj3.metodoX(10, 100)" é o terceiro método da classe b, onde é pego o primeiro argumento m=10, chama-se o segundo método da classe b, passando o argumento 10 (já explico), onde retorna 1000, é somado com o resultado do primeiro método da classe b que é 100, resultado 1100, nesse caso é ignorado o segunda argumento o "n" pois não tem aplicação na terceira função, como foi passado o argumento "m" na terceira função, ele se torna o "n" na segunda, métodos em java recebem o parâmetro e guardão na variável o método é chamado da seguinte forma metodoX(10);
Espero ter ajudado a entender.


How to install google-api-python-client via terminal

Question: i'n trying to install google-api-python-client package, using terminal and
pip install --upgrade google-api-python-client

the same result for
sudo -H  pip install --upgrade google-api-python-client

also I found, that someone recommends to use such approach:
sudo chown -R zkid18 /Users/zkid18/Library/Logs/pip
chown: /Users/zkid18/Library/Logs/pip: No such file or directory

and
sudo chown -R zkid18 /Users/zkid18/Library/Cashes/pip
chown: /Users/zkid18/Library/Cashes/pip: No such file or directory

Tje same result, when I'm installing via Pycharm
My exception
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 736, in install
    requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 742, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip/utils/init.py", line 267, in renames
    shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-uxDRkx-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'
Answer: Install with virtualenv
virtualenv temp
source temp/bin/activate
pip install --upgrade google-api-python-client

or ignore Six
sudo pip install --upgrade google-api-python-client --ignore-installed six

Comment: Is it possible to install without venv?


When using Views Bulk Operations, the options for Rule Components are not shown in the VBO drop down for all users

Question: When I am logged in as the root admin, I am able to create Rule Components (rule and rule sets) and have them appear in the View Bulk Operations (VBO) settings menu as an option for a VBO view table column.  As the root admin, I can also navigate to the view's page and successfully perform the Rule Component on table entries using the VBO interface.
However, when I log in as another user (seemingly regardless of role or permission) The Rule Component options which were enabled for the VBO column are no longer available.  It appears that some sort of permission is blocking them.  It is not obvious which permission (or if it is a permission) is blocking the Rule Component Options so they don't appear in the VBO list.
Does anyone have experience with this problem and knows a way to get Rule Components to appear in the VBO drop down in a view for all users?
Answer: If you are adding operations using Rules Component then you have to set the permission.
Edit your rule component and under the settings there will be Configure access for using this component with a permission, set your permission here.
Comment: Yeah, that was the root cause of this problem (too)


Mixpanel - Is there a way to distinguish first time visitors from others?

Question: We have Mixpanel currently setup in our website, and we are following the recommendation around using alias (when signing up) and identify (when users logs in).
One thing I can't get my head around is if it's possible with Mixpanel to see the behaviour users (logged in or not) have on theirs first visit to the website.
Since Mixpanel uses a cookie, I supposed I could manually check that, but just wondering if there is something already built for it.
Answer: You need to do this manually, there are no solutions for that task.
Mixpanel was not created for tracking visits, new unique users are tracked in Google Analytics.
Mixpanel places a timestamp for every event you track.
So, when you watch Retention it generally knows when the first ever event for each user occured.
If you want to analyze first visits in Mixpanel Funnels (not Retention) create event called "First Visit" and fire it using this scenario (you need to write additional code to your website of course):

On each user visit to your website ask mixpanel cookie if it already has UserID, not just an AnonymousID (watch Resources-Cookies in Google Chrome developers mode for parameters))
If it doesn't - fire IDENTIFY method (with anonymousID) and then your "First Visit" event.
If it does - do nothing.
Then, when user SignsUp - fire ALIAS method to merge previously identified anonymous visit with the newly identified registered user so that "First Visit" event will be tied to the registered UserID.

Note! This scenrio is suitable only if you use your own database userIDs and only if user visits your website from one device. (Unfortunately if user first came from PC and then registered from Tablet - the First Visit event tied in his profile will be from Tablet, not from PC. This is how cookie works)


Flag mail with sieve to make them appear colored in MUA

Question: I want to flag mails with sieve to make them appear colored in MUA.
Use case: On a very high traffic technical mailing list, there is a community member with a brilliant mind. I want to highlight his posts to make them more visible.
I want to do this with sieve (and not in the MUA) since I use different MUAs.
The result should look like this screen shot of thunderbird:
Answer: You can use sieve like this:
require "imap4flags";

if header :contains "from" ["malcolmt"] {
   addflag "$label5";
}

Here is the list of available hard-coded tags:
0 – Remove all tags,
1 – Important,
2 – Work,
3 – Personal,
4 – To Do,
5 – Later

List of flags is from http://www.grimeton.com
BTW, I choose 5 because I like the color. I don't care for the meaning in this context.


problem when UIWebView to display gif image

Question: I want to display multiple images in a view. Images are downloaded from internet and are gif format.
This is what I did, but only the default broken icon is shown.
_images is a NSArray stored the path of image files
NSMutableString *html = [NSMutableString string];

for (NSString *str in _images) {
    [html appendFormat:@"", str];
}

[_webView loadHTMLString:html baseURL:nil];

I tried this and image are displayed so I believe UIWebView are capable to display my images.
NSData *data = [NSData dataWithContentsOfFile:[_images lastObject]];
[_webView loadData:data MIMEType:@"image/gif" textEncodingName:@"UTF-8" baseURL:nil];

Or is any other good way to display multiple images? Otherwise I may have to create a UIImageView for each image and put them into a scroll view.
Answer: The UIWebView should not have problems displaying .GIF images (as you proved in your test). The broken icon typically appears when the image is not found at the URL you provided. So might want to check your image URL (by opening the URLs in any browser).
Personally I would rather use a UIScrollView with UIImageViews in it. UIWebViews tend to be rather slow in loading and displaying their content. And if you want to react to user action on the images, UIWebView has another disadvantage: you need to implement some javascript event handling and there is a short but noticeable delay when the user taps on one of the images inside the UIWebView. If you go further and want to add swipe or other gesture recognition on your images you need to import a javascript library that does that. If you don't need user interaction on your images those disadvantages don't really count in your case. On the other hand using a UIWebView is quite handy because it automatically loads it's content asynchronously.
The UIScrollView with UIImageViews solution makes user interaction handling really easy. Just add UIGestureRecognizers to you images and off you go. On the other hand, if you have a lot of images or large images you cannot load them all at the same time or you'll run into memory warnings. So you might have to add some logic to only load the images that are currently displayed and release the ones that are not visible. You also have to implement async loading for your images to not block the scrolling while images are loading.
If your images all have the same size, you could use a UITableView to display the images and use it's build-in reuse of table cells to keep the memory footprint small. You still have to implement async loading though.
Anyway, I think there is no right or wrong in this case. If you do not need user interaction sing the UIWebView is easier and faster to implement but IMHO the UIScrollView / UITableView will still have the better user experience.


Closed Form Solution for Recurrence Relation

Question: Is it possible to calculate the closed form solution for the following recurrence relation?
$$
T(n) = T\left(\frac{n}{2}\right) + T\left(\frac{n}{2} + 1\right) + \frac{n}{2}
$$
I am trying to teach myself about this stuff, and I see that it is similar in form to
$$
T(n) = \alpha T\left(\frac{n}{b}\right) + f(n)
$$
But the second term of $T\left(\frac{n}{2} + 1\right) $ is messing me up.
Comment: For which values of $n$ do you want $T(n)$ to be defined?
Comment: But each recursion relation for n even calls for some value T(2k+1)... You ought to make the model more precise before there is a real question here.
Comment: For all even integers greater than 1.
Comment: @lsowen: $T(2)=T(1)+T(2)+1$ is going to give you some headaches, then. Or $T(4)=T(2)+T(3)+2$, if $T(2)$ is given by an initial condition.
Answer: For $n=0$, this yields $T(0)=T(0)+T(1)$. For $n=2$, this yields $T(2)=T(1)+T(2)+1$. Thus $T(1)=0=T(1)+1$, which might be seen as a problem.


Putting multiple Add to cart links / buttons on a page

Question: I'm writing a series of blog posts on my eCommerce site. For example, "10 easy breakfasts for the busy mom/dad". Under each "breakfast idea", I want to put a small block like "Items you'll need". This "items you'll need" will have links to products in our shopping site.
The idea is that if someone likes a blog post or one of the "receipes", they can immediately click on the products below and add them to cart. I don't want them to be taken away from the page they are reading though, because that would be annoying.
They will need some indication that the product was added to cart, so maybe a green tick or "Added!" label will need to show up.
When you get to bottom of the blog post, there should be a block "Products you have in your cart" so that they review and can choose to check out if they want.
I've found these articles & modules:
Creating Drupal Commerce add to cart links
,
Commerce Add to Cart Ajax,
Custom Add to Cart Link
But I'm not sure which is the way to go considering my requirements:

Curated product links / thumbnails in blocks
Clicking sends ajax signal to cart to add product
There is an indication that the product was added "Added!" or a tick or border highlight.
If the same product is on multiple blocks in the page, when I click one block, it should update on all the blocks.
Ajax stuff should be robust on mobile devices

I've never done this before, Drupal ajax & custom cart stuff, so I wanted to ask your advice on what to consider before moving ahead. I want to do it in the simplest and most robust way possible. If I can avoid custom code and sandbox code, that would be ideal. Thanks.
Answer: jQuery is our friend.
Create a DIV for every product that will perform an ajax request (on click) to a path that will update your cart and then retrieve the cart contents. Ex. /ajax/cart?op=add&pid=idOfProduct
Create a path (hook_menu) where you will send the add to cart message or other messages that you want to send to the cart (item removal for example).
This path will update the cart to your needs based on the parameters you send it.
The response of the path could be in full HTML for simplicity, with the updated and already rendered cart.
Replace the current cart with the new contents. It's not simple but it will work.
Hope that helps!
Comment: You're suggesting jquery + REST commerce api? I found [Commerce Services Resources](https://www.drupal.org/project/commerce_services) and [Services Commerce](https://www.drupal.org/sandbox/drupalista-br/1283494) modules that could do the REST api. How do I work with jquery ajax on mobiles? What do I look out for?
Comment: No. That's a solution, but requires a more work. I suggest you to create a simple url to achieve the exact operations you need and update the cart. Then render the cart with the method you prefer: a view, a block, etc. Then replace the contents of the cart with the updated content.
Comment: For Ajax and jQuery you can start with $.ajax() http://api.jquery.com/jquery.ajax/
Comment: Also see hook_menu to declare your ajax path in Drupal. One option to output the the rendered cart is drupal_json_output, or just do a print of your cart and then exit (the ugly way).
Comment: Hey thanks for the helpful information man. I'll reply more back here when I start working on it.


Do unbalanced observations contribute to identification in fixed effects models?

Question: I am quite confused on how to interpret my regression results.
I want to estimate the effect of tariff changes $\tau_{st}$ in sector $s$, period $t$ on firm $i$ employment. I have two time periods (4 years apart) and want to use time and/or firm fixed effects. This is the base model:
$$y_{ist} = \beta \tau_{st} + \lambda_t + \mu_i + \epsilon_{ist}$$
The thing is that not all $i$ firms are observed in both time periods. There are either leavers, entrants, or continuing firms.
I have two questions related to the sources of identification of $\beta$ - Ideally, I would want to use cross-sectoral variation in tariff changes to identify it. Here it goes:
1 - Do leavers and entrants contribute to the estimation if I include $\mu_i$? How so? I understand they would in case I had $\mu_s$ instead. If not, would I get the same estimates by just dropping such observations?
2 - There a few firms that, although present in both $t=1$ and $t=2$, change sectors $s$ from period to period. Do these units also help with the identification of $\beta$ if I use the model above?
If I wanted to consider cases in which a firm may react to the policy change by moving to a sector with higher tariffs on the following period, which fixed effect structure would do so?
Answer: I am going to change your notation slightly and explicitly write $\tau$ depending on $i$ as $\tau_{ist}$, even if in practice, $\tau_{ist}$ is only determined by $s,t$. One of the most helpful theorems for trying to understand what variation a regression is using to identify a coefficient is the Frisch-Waugh-Lovell theorem. Specialized to your problem, a version of it states that $\beta$ is equivalent to the following
$$\hat \beta = \frac{\hat{\mathbb E}[y_{ist}(\tau_{ist} - \hat \tau_{ist})]}{\hat{\mathbb E}[(\tau - \hat\tau_{ist})^2]}$$
where $\hat\tau_{ist}$ is the predicted value of $\tau_{ist}$ from the the least squares regression $\tau_{ist} = a_t + b_i + \delta_{ist}$, and $\hat{\mathbb E}$ is my notation for the sample mean. So to answer your question 1, it would suffice to show two facts:

$\tau_{ist} - \hat\tau_{ist} = 0$ for any observation $i$ that is only present in one of the two time periods
$\hat \tau_{ist}$ does not depend on the value of $\tau_{jst}$ for any observation $j$ that only shows up in one time period

Point 1 is easy enough to see: if this was not true, then by changing the parameter $b_i$ by amount $\tau_{ist} - \hat\tau_{ist}$, we could decrease the least squares objective, which would contradict that $\hat\tau_{ist}$ is the least squares fit. Point 2 is also fairly simple. The basic idea is that by the argument I just made to prove point 1, for all $j$ that only shows up in one period, we can always choose $b_i$ in such a way that $\tau_{jst} - \hat\tau_{jst} = 0$. But this means that the least squares fit for the model $\tau_{ist} = a_t + b_i + \delta_{ist}$ can always be obtained by first fitting the model only for individuals showing up in both time periods and then setting $b_j$ accordingly for the rest and importantly, this second step does not change any of the fits $\hat\tau_{ist}$ from the first step.
Once we have shown these two points, using our expression for $\hat\beta$ that observations only showing up in one period do not affect the estimate: By point 1, their contribution to the sample mean is 0, and by point 2, they do not affect $\hat\tau_{ist}$ for any $i$ that did show up in both periods.
To your point 2, there is no reason why firms that switch should not affect your estimate for $\beta$. From the perspective of OLS, this structure that you imposed that $\tau$ is sector specific is not used for estimation at all, so individuals experiencing a change in $\tau$ because they switched sectors should be treated no differently than individuals experiencing a change in $\tau$ because their sector experienced a change in $\tau$.
Finally, to your last point, it seems that a FE model might just not work if your concern is that firms are selecting into tariff levels based on their reactions to policy changes. In particular, these FE models tend to rely on a "common trends" assumption or something similar, but selection into tariffs may arise precisely because firms with different trends select differently. I do not have enough context about your problem to offer any concrete advice with any certainty, but one direction you might consider is looking for covariates that explain why firms are switching industries.
Comment: You would probably want to work though the algebra yourself a bit more closely, but here is where I would start. First, recall that the usual OLS standard variance are given by $\frac1n (X'X)^{-1} \hat\sigma^2$. Aside from the factor of $1/n$, we can think of this formula as an in-sample estimator for the ratio of the variance of the error term ($\hat \sigma^2$) and the variance of the covariates ($X'X$).
Comment: One can use the law of total variance to get $Var(\varepsilon) = E[Var(\varepsilon | removed)] + Var(E[\varepsilon | removed])$ (where removed is an indicator for whether the observation only appeared in one period). Recall additionally that Var(\varepsilon | removed) = 0. Since $E[\varepsilon | removed = 1] = E[\varepsilon] = 0$, the second term vanishes, so we are left with $Var(\varepsilon) = (1-p) E[Var(\varepsilon | removed = 0)]$ where $p$ is the proportion of observations that are removed.
Comment: Let $k = (1-p)n$ be the number of units left after removal. This argument shows that $1/n \hat\sigma^2 = 1/k (\hat\sigma')^2$ where $(\hat\sigma')^2$ is the variance of the residuals of the model with the perfectly predicted observations removed. A similar argument from the law of total variance should on the other hand show that the denominator $X'X$ in the model with observations removed only gets larger, which yields what you see, that the standard errors go down when you keep only units present in both periods.
Comment: Another way to think about what is going on is that the OLS standard errors given by most software packages do not by default assume homoskedasticity, which is violated in a pretty extreme way when the error term for some of the observations (i.e. the ones you don't see in both periods) are literally 0. Interestingly enough, this seems to be one of those rare examples where not accounting for heteroskedasticity is actually making your standard errors larger.
Comment: thanks for the awesome answer! Just a quick follow-up: after running a test with my data, I do find that the estimates for the regression coefficients are the same. However, my standard errors are not - they are much lower when keeping only units present on both periods. Is there a reason for this?


Density estimation as an optimization problem

Question: Density estimation is the estimation of a probability density function from observed data. Can some of the common approaches to density estimation, such as kernel density estimation, be formulated as infinite-dimensional optimization problems? That is, can we formulate them as the problem of optimizing some functional of the resulting PDF, subject to some constraints?
In particular, I'm interested in the result of the following procedure: Suppose we have some samples $x_i \in \mathbb{R}^n$ from some unknown PDF with support in $\Omega \subseteq \mathbb{R}^n$. What PDF $f$ with support in $\Omega$ solves the following optimization problem?
Maximize the likelihood of the samples, i.e.
$$L(f) = \prod_i f(x_i)$$
subject to the constraint that the differential entropy of $f$
$$H(f) = -\int_\Omega f(x) \log f(x) \;\mathrm{d}x$$
is equal to some number $h$. If I understand correctly, this gets rid of the trivial maximum-likelihood solution of putting deltas at each sample, since deltas have differential entropies of $-\infty$. One might further impose a condition such as smoothness.
Comment: Something vaguely related that might be of interest: given some complicated posterior distribution, [this paper](https://arxiv.org/abs/1805.01648) and its predecessors view Langevin MCMC as a deterministic optimization in the space of probability distributions.
Comment: @user76284 where have you seen this optimization problem before?
Comment: @develarist Maximum likelihood under constrained entropy? Just something I came up with that I thought might be related to density estimation.
Answer: (I'll answer the second question, about the results of your maximum likelihood with fixed differential entropy procedure; I don't know the answer to the first, about whether KDE can be phrased as optimizing some objective functional.)
Without additional constraints such as bounds on the derivatives, the problem is ill-posed: you can achieve any finite likelihood with fixed differential entropy.
Let $f_0$ be any density over $\Omega$ with differential entropy $h$. If $\log \lvert \Omega \rvert < h$, this is impossible and the problem is unsatisfiable; otherwise, take it to be e.g. uniform over some subset of $\Omega$ with appropriate volume.
Then define
$$
f(x)
= \begin{cases}
q & \text{if } x = x_i \text{ for some } i \\
f_0(x) & \text{otherwise}
\end{cases}
$$
for any finite $q$. This has likelihood $q^m$, where $m$ is the number of points $x_i$; since we've only modified $f_0$ on a set of measure zero, $f$ still has integral 1 and differential entropy $h$. So you can make the likelihood as high as you want.
Of course, changing the density function on a set of measure zero is in some ways "not fair"; the distribution itself won't be altered, for example.
But we can achieve essentially the same thing with continuous, or even $C^\infty$ density functions; just make a very narrow bump at each $x_i$. The next section shows formally that we can do that, but it's just this intuition in equations.

Let $f_0$ be a continuous (or $C^\infty$) density of differential entropy $Q$ whose support does not include any of the $x_i$ (or a ball around them). This makes the calculations much easier, as we don't have to worry about interactions between $f_0$ and the bumps we'll put at each $x_i$, but is not fundamental to the approach.
Let $\ell < \min_{i,j} \lvert x_i - x_j \rvert$ and also smaller than the distance from any $x_i$ to the support of $f_0$.
Define $$f_i(x) = \frac1\ell g\left( \frac{x - x_i}{\ell} \right),$$
where $g$ is the pdf of a mean-zero distribution with continuous (or $C^\infty$) density and support on a subset of the unit ball.
Many kernel functions
would work, for example.
Let $g(0) = g_0$ so that $f_i(x_i) = \frac1\ell g_0$,
and let $H[g] = \int g(x) \log g(x) \,\mathrm d x = \eta$
so that $H[f_i] = \eta - \log \ell$.
We'll take a mixture between $f_0$ and the $f_i$, for some $\alpha \in (0, 1)$ to be determined later:
$$
f(x) = (1-\alpha) f_0(x) + \frac{\alpha}{m} \sum_{i=1}^m f_i(x)
.$$
Then we have
$$
\int f(x) \,\mathrm d x
= (1 - \alpha) \int f_0(x) \,\mathrm d x
+ \frac{\alpha}{m} \sum_{i=1}^m \int f_i(x) \,\mathrm d x
= 1
,$$
and
$$L(f) = \left( \frac{\alpha}{m \ell} g_0 \right)^m = \left( \frac{g_0}{m} \right)^m \left( \frac{\alpha}{\ell} \right)^m
.$$
The first term is constant; we want to choose $\alpha$, $\ell$ so as to maximize $\alpha / \ell$ and hence $L(f)$.
Our constraint on $\alpha$ and $\ell$ is determined by
\begin{align}
     \int f(x) \log f(x) \,\mathrm{d}x
  &= \int (1-\alpha) f_0(x) \log\left( (1-\alpha)  f_0(x) \right) \,\mathrm{d}x
   + \sum_{i=1}^m \int \frac{\alpha}{m} f_i(x) \log\left( \frac{\alpha}{m} f_i(x) \right) \mathrm d x
\\&= (1-\alpha) H[f_0] + (1-\alpha) \log(1 - \alpha)
   + \frac\alpha m \sum_{i=1}^m H[f_i]
   + \frac\alpha m \sum_{i=1}^m \log \frac\alpha m
\\&= (1-\alpha) Q + \alpha \eta - \alpha \log \ell + (1-\alpha) \log(1 - \alpha) + \alpha \log \alpha - \alpha \log m
.\end{align}
Setting this equal to $h$,
dividing both sides by $\alpha$,
and moving some terms,
we get
$$
\frac{Q - h}{\alpha} + \frac{1-\alpha}{\alpha} \log(1 - \alpha) + \log \frac\alpha\ell = Q - \eta + \log m
.$$
We could directly solve this for $\ell$, but the expression is little messy and we don't care about the particular value of $\ell$.
It's sufficient to note that as we drive $\ell \to 0$,
we'll have $\alpha \to 0$ as well; we care about the relative rate.
We can use
$$\log(1-\alpha) = - \alpha - \mathcal O(\alpha^2)$$
so that
$$
\frac{1-\alpha}{\alpha} \log(1-\alpha)
= - 1 + \alpha - \mathcal O(\alpha)
= -1 \pm \mathcal O(\alpha)
.$$
Thus
$$
\frac{Q - h}{\alpha} \pm \mathcal O(\alpha) + \log \frac\alpha\ell = 1 + Q + \log m - \eta
$$
and so
$$
\frac\alpha\ell
=
\underbrace{\exp\left( 1 + Q + \log m - \eta \right)}_\text{constant}
\exp\left( \frac{h - Q}{\alpha} \pm \mathcal{O}(\alpha) \right)
.$$
As long as $Q < h$,
we have $\frac\alpha\ell \to \infty$ as $\alpha \to 0$,
so $L(h) \to \infty$ as $\alpha \to 0$.
In the limit $\ell \to 0$, this converges to $f_0$ plus delta functions at each of the $x_i$ (as before). But for any finite $\ell$, we know we can balance the entropy of each nearly-a-delta-function spike with the entropy of $f_0$ appropriately so that the total is $h$. Thus, as before, for any finite target likelihood we can find a distribution with that likelihood and differential entropy $h$.

A constraint such as a Lipschitz density would correspond in this setting to a constraint on $\ell$, preventing us from driving the density to infinity.
It might be possible to derive the maximum-likelihood estimator among $L$-Lipschitz densities with differential entropy $h$. This might look something like:

Put peaks as high as possible at each $x_i$.
Decrease away from each peak uniformly with slope $L$.
Stop decreasing at some base level uniform over $\Omega$.

This likely would not actually be the MLE in this family, but you might be able to get a linear program or something that gives a solution kind of like this.
Comment: Thank you for your comprehensive answer! I wonder what other constraints on this optimization problem might yield interesting behaviour.
Comment: Do you think constraining the [total variation](https://en.wikipedia.org/wiki/Total_variation) of the density would yield something similar?
Comment: @user76284 That might work; not sure.


flutter problem: dataColumn width issue and How to remove rowDivider from dataTable?

Question: here i got width issue for data table and I also want every rowDivider will be remove,
and here I use animation, if you have any idea to improve animation then tell me.
here i got width issue for data table and I also want every rowDivider will be remove,
and here I use animation, if you have any idea to improve animation then tell me.
this is my full code
<code>import 'package:bonanza_flutter/Constants/constants.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double _height = 60.0;
  bool _isExpanded = false;

  Future<bool> _showList() async {
    await Future.delayed(Duration(milliseconds: 300));
    return true;
  }

  Future<bool> _showList1() async {
    await Future.delayed(Duration(milliseconds: 10));
    return true;
  }

  bool isOnPMS = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: AppBar(

      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // imageSlider(),
            pmsData(),
            // advantages(),
            // products(),
            Container(
              height: 20,
            )
          ],
        ),
      ),
    );
  }
}

extension WidgetExtension on _HomePageState {
  pmsData() {
    return Container(
      color: lightBlue,
      child: Column(

        children: [
         Padding(
           padding: const EdgeInsets.all(20.0),
           child: Column( crossAxisAlignment: CrossAxisAlignment.start,children: [
             Row(
               mainAxisAlignment: MainAxisAlignment.spaceBetween,
               children: [
                 Text(
                   "PMS",
                   style:
                   TextStyle(fontSize: tSize16, fontWeight: FontWeight.w500),
                 ),
                 Row(
                   children: [
                     Container(
                       width: 22,
                       height: 22,
                       decoration: BoxDecoration(
                         borderRadius: BorderRadius.circular(3),
                         color: skyBlue,
                       ),
                       child: Icon(
                         Icons.arrow_back_ios_outlined,
                         color: Colors.white,
                         size: 17,
                       ),
                     ),
                     SizedBox(
                       width: 20,
                     ),
                     Container(
                       width: 22,
                       height: 22,
                       decoration: BoxDecoration(
                         borderRadius: BorderRadius.circular(3),
                         color: skyBlue,
                       ),
                       child: Icon(
                         Icons.arrow_forward_ios_rounded,
                         color: Colors.white,
                         size: 17,
                       ),
                     ),
                   ],
                 )
               ],
             ),
             SizedBox(
               height: 8,
             ),
             Text(
               "ICICI Prudential PMS",
               style: TextStyle(
                   fontSize: tSize14, fontWeight: FontWeight.w500, color: skyBlue),
             ),
             SizedBox(
               height: 12,
             ),
             Row(
               mainAxisAlignment: MainAxisAlignment.spaceBetween,
               children: [
                 Column(
                   crossAxisAlignment: CrossAxisAlignment.start,
                   children: [
                     Text(
                       "\u{20B9} 50,00,000",
                       style: TextStyle(
                           fontSize: tSize11,
                           fontWeight: FontWeight.w500,
                           color: blackColor),
                     ),
                     SizedBox(
                       height: 5,
                     ),
                     Text(
                       "ICICI Prudential PMS",
                       style: TextStyle(
                           fontSize: tSize11,
                           fontWeight: FontWeight.w500,
                           color: greyColor),
                     ),
                     SizedBox(
                       height: 14,
                     ),
                     Text(
                       "\u{20B9} 2,02,993 (+4.06%)",
                       style: TextStyle(
                           fontSize: tSize11,
                           fontWeight: FontWeight.w500,
                           color: green2Color),
                     ),
                     SizedBox(
                       height: 5,
                     ),
                     Text(
                       "Gains & Loss",
                       style: TextStyle(
                           fontSize: tSize11,
                           fontWeight: FontWeight.w500,
                           color: greyColor),
                     ),
                   ],
                 ),
                 Column(
                   crossAxisAlignment: CrossAxisAlignment.start,
                   children: [
                     Text(
                       "\u{20B9} 52,02,993",
                       style: TextStyle(
                           fontSize: tSize11,
                           fontWeight: FontWeight.w500,
                           color: blackColor),
                     ),
                     SizedBox(
                       height: 5,
                     ),
                     Text(
                       "Current Market Value",
                       style: TextStyle(
                           fontSize: tSize11,
                           fontWeight: FontWeight.w500,
                           color: greyColor),
                     ),
                     SizedBox(
                       height: 14,
                     ),
                     Text(
                       "\u{20B9} 5",
                       style: TextStyle(
                           fontSize: tSize11,
                           fontWeight: FontWeight.w500,
                           color: blackColor),
                     ),
                     SizedBox(
                       height: 5,
                     ),
                     Text(
                       "Total Holdings",
                       style: TextStyle(
                           fontSize: tSize11,
                           fontWeight: FontWeight.w500,
                           color: greyColor),
                     ),
                   ],
                 ),
                 SizedBox(
                   width: 0,
                 )
               ],
             ),
           ],),
         ),
          AnimatedContainer(
            duration: Duration(milliseconds: 300),
            height: _height,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5),
            ),

            // padding: EdgeInsets.only(left: 15, right: 15),
            child: Column(
              children: [
                _isExpanded
                    ? SizedBox.shrink()
                    : FutureBuilder(
                        future: _showList1(),

                        /// will wait untill box animation completed
                        builder: (context, snapshot) {
                          if (!snapshot.hasData) {
                            return SizedBox();
                          }
                          return Center(
                            child: Padding(
                              padding: const EdgeInsets.only(
                                  top: 20.0, bottom: 00, left: 70, right: 70),
                              child: SizedBox(
                                height: 25,
                                width: 100,
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      primary: skyBlue,
                                      shadowColor: Colors.transparent),
                                  onPressed: () {
                                    setState(() {
                                      isOnPMS = !isOnPMS;
                                      if (!_isExpanded) {
                                        setState(() {
                                          _height = 350;
                                          _isExpanded = true;
                                        });
                                      } else {
                                        setState(() {
                                          _height = 50;
                                          _isExpanded = false;
                                        });
                                      }
                                    });
                                    print(_isExpanded);
                                  },
                                  child: Text("View More"),
                                ),
                              ),
                            ),
                          );
                        }),
                _isExpanded
                    ? FutureBuilder(
                        future: _showList(),
                        builder: (context, snapshot) {
                          if (!snapshot.hasData) {
                            return SizedBox();
                          }
                          return Padding(
                            padding: const EdgeInsets.only(
                                top: 20.0, bottom: 00, left: 0, right: 0),
                            child: Column(
                              children: [
                                DataTable(
                                  columns: const <DataColumn>[
                                    DataColumn(
                                      label: Text(
                                        '#',style: TextStyle(color: Colors.white),
                                      ),
                                    ),
                                    DataColumn(
                                      label: Text(
                                        'STOCK',style: TextStyle(color: Colors.white),
                                      ),
                                    ),
                                    DataColumn(
                                      label: Text(
                                        'SECTOR',style: TextStyle(color: Colors.white),
                                      ),
                                    ),
                                    DataColumn(
                                      label: Text(
                                        'WEIGHT',style: TextStyle(color: Colors.white),
                                      ),
                                    ),
                                  ],
                                  rows: const <DataRow>[
                                    DataRow(
                                      cells: <DataCell>[
                                        DataCell(Text('1')),
                                        DataCell(Text('TCS')),
                                        DataCell(Text('Global')),
                                        DataCell(Text('11%')),
                                      ],
                                    ),
                                    DataRow(
                                      cells: <DataCell>[
                                        DataCell(Text('2')),
                                        DataCell(Text('DMART')),
                                        DataCell(Text('Consumers')),
                                        DataCell(Text('10%')),
                                      ],
                                    ),
                                    DataRow(
                                      cells: <DataCell>[
                                        DataCell(Text('3')),
                                        DataCell(Text('ICICIBANK')),
                                        DataCell(Text('Financials')),
                                        DataCell(Text('12%')),
                                      ],
                                    ),
                                    DataRow(
                                      cells: <DataCell>[
                                        DataCell(Text('4')),
                                        DataCell(Text('RELIANCE')),
                                        DataCell(Text('Industrial')),
                                        DataCell(Text('13%')),
                                      ],
                                    ),
                                  ],
                                  dividerThickness: 0,
                                  headingRowColor:
                                      MaterialStateColor.resolveWith(
                                          (states) => greyColor),
                                  headingRowHeight: 30,
                                ),
                                Center(
                                  child: Padding(
                                    padding: const EdgeInsets.only(
                                        top: 20.0,
                                        bottom: 00,
                                        left: 70,
                                        right: 70),
                                    child: SizedBox(
                                      height: 25,
                                      width: 100,
                                      child: ElevatedButton(
                                        style: ElevatedButton.styleFrom(
                                            primary: skyBlue,
                                            shadowColor: Colors.transparent),
                                        onPressed: () {
                                          setState(() {
                                            isOnPMS = !isOnPMS;
                                            if (!_isExpanded) {
                                              setState(() {
                                                _height = 350;
                                                _isExpanded = true;
                                              });
                                            } else {
                                              setState(() {
                                                _height = 50;
                                                _isExpanded = false;
                                              });
                                            }
                                          });
                                          print(_isExpanded);
                                        },
                                        child: const Text('View Less'),
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          );
                        })
                    : SizedBox.shrink(),
              ],
            ),
          )
        ],
      ),
    );
  }
}

</code>
I want like this dataDable.

this is my ui which I created.
Answer: Wrap DataTable with SingleChildScrollView and set scrollDirection to horizontal.
Use TableBorder to remove divider.


Spring MVC with Sass

Question: I am working on a Spring MVC project and extending its capabilities to use Sass. I installed Sass correctly and verified that. I selected the compiler (Sass.bat) in the netbeans configurations but when I save the Scss file I don't find the output.
I know it's a file directory mapping issue. I tried several combinations of relative files URL but can't get it to work.
Thanks in advnace.
Answer: This is the correct path that should be for the scss files location:
/WEB-INF/resources/scss
and this for the css files generation location
/WEB-INF/resources/css

Spring MVC with Sass


Packing of parallelograms with sides $1$ and $\sqrt{2}$ and angle $45^{\circ}$ in a rectangular container

Question: If $ABCD$ is a parallelogram such that $\angle BAD=\frac{\pi}{4}$, $AB=\sqrt{2}$, $AD=1$ then we shall say that $ABCD$ is a good parallelogram. Parallelograms can be rotated by any angle.
a) Prove that in a rectangular container $2 \times n$ ($n \ge 2$) cannot be packed more than $2n-2$ good parallelograms (packing must be without overlaps between parallelograms).
b) Prove that in a rectangular container $4 \times 4$ cannot be packed more than $12$ good parallelograms (packing must be without overlaps between parallelograms).
My work. It is easy to pack $2n-2$ good parallelograms into rectangular container $2 \times n$. The area of the good parallelogram is $1$. The area of the rectangular container $2 \times n$ is $2n$. Obviously, parallelograms will not be able to cover every region of the rectangular container. Therefore, in a rectangular container $2 \times n$ ($n \ge 2$) cannot be packed more than $2n-1$ good parallelograms. But I have no idea how to improve the evaluation for one parallelogram.
Comment: I don't think it makes a difference, but are reflections allowed?
Comment: Yes, reflections allowed.
Comment: @ Sambo It seems to me that the proof would be much easier if reflections were not allowed.
Answer: My proof for $2\times n$ by induction:
$\\$
Let us show the statement is true for $2\times 2$: (The proof includes geometric figures can be seen at the link: https://www.geogebra.org/classic/khfaznnu .) Showing $3$ parallelograms cannot fit into $2\times 2$ rectangle will be enough. Lets consider barycentres of these parallelograms. In order to fit a parallelogram, the distance between its barycentre and vertices of rectangle must be at least $\dfrac{\sqrt5}{2}$. Also consider that the distance between barycentres of $2$ parallelogram is at least $\dfrac{\sqrt2}{2}$. So, if we can fit $3$ parallelograms, we can fit their barycentres inside $EHFG$ (I mean it is the figure outside of $4$ circles. I don't know if the figure has a name. If has, a comment  will be appreciated.). However, as can be seen at the link, we cannot fit an triangle with sides are length at least $\dfrac{\sqrt2}{2}$ because drawing a circle with center $G$ and radius $\dfrac{\sqrt2}{2}$ shows us the best proper triangle is $GPQ$ but $|PQ|\le\dfrac{\sqrt2}{2}$  (note that the most distant point of a point inside $EHFG$ is a vertex of $EHFG$ so drawing such circle is logical), thus we cannot fit $3$ parallelograms into $2\times 2$ rectangle (all sides of the triangle has some region outside of $EHFG$ thus any rotating or movement cannot fit it.).
$$\\$$
Let it is also true for $2\times k$ , $k>1$. In order to prove it for $2\times (k+1)$ , it is enough to show that we cannot fit $3$ new "good parallelograms" that has some region in added new $2\times 1$ rectangle. Suppose we can fit, then at least $2$ of "good parallelograms" must also have some region in rectangle $2\times k$ but in that case we can not fit the third "good parallelogram" into new $2\times 1$ rectangle because if we can, then the last parallelogram must cover half of the longer sides of the $2\times 1$ rectangle, so it intersects one of the $2$ other parallelograms. (Note that these $2$ parallelograms cannot both in upper half or lower half of the $2\times 1$ rectangle) Also we can not fit the last parallelogram so that it has some region in rectangle $2\times k$ because in that case we would have $3$ "good parallelograms" which covers at least $1$ unit height inside $2$ unit height (here I suppose in a rectangle $2\times n$, $2$ is height and $n$ as width).
$\\$
Thus, we can add "at most" $2$ "good parallelograms" which has some region in $2\times 1$ rectangle and it shows that the statement is also true for $2\times (k+1)$
Comment: For $n=1$ the statement is not true, since then $2n-2=0$, but one parallelogram fits into the $2\times 1$ rectangle.
Comment: Now you have to prove the case $2\times 2$. And how you handle the case described in my answer? There three parallelograms intersect the new rectangle $2\times 1$.
Comment: I edited my solution with proving $2\times 2$ case, I know also I should handle with your answer, I will try to improve my solution tomorrow (as soon as possible).
Comment: Oops, you are right. Also the question is asked while $n\ge2$. However, we can start the induction with $n=2$ and continue as in the solution. I edited it.
Comment: It is not necessary that the centers form an equilateral triangle, they could be at the points $K,F$ and $E$, for example, and the distance between them is greater than or equal to $\frac{\sqrt{2}}2$.
Answer: In general the packing problem is a very difficult problem. If you want to give an inductive proof, you have to eliminate the following possibility, in which 3 parallelograms have some region in the new added 2×1 rectangle.


What do the numbers 2 & 3 mean (duplet/tuplet/finger indication?) in this first bar of a song?

Question: I was looking for a simple anime song piece where I encounter this piece whose first bar does not make sense to me (I uploaded the first bar picture ).
Especially what is meant by 2 and 3 at the top of the first two notes? Is it tuplet or finger indication?
Thank you.
Answer: The 2 is a fingering notation; the 3 is over the middle and in a different font and size, so I can tell that the 3 is the indication to play a triplet (and the measure only adds up for a triplet). So that 3 doesn't necessarily mean to finger the first A with the 3rd finger, though you may wish to.
The notation means:

Play the F♯ with your 2nd finger
Play those three eighth notes as eighth note triplets

(This is not super clear upon viewing. Good question!)
Comment: I thought so about 3 being a triplet, otherwise measure does not add up just like you have said. I was confused because of 2 as I did not notice the front difference.
Answer: The 2 is a fingering indication.
The 3 (which is in italics and a larger font) is indicating that the three notes are a triplet - so the first three notes take one beat.
Hope that helps.
Answer: Well, like others said: the font and positioning (and beaming) make clear that the first is a fingering indication and the second is a triplet indication, but...
If I were playing this, I'd rather use a "1" on the first note, then a "3" where the triplet "3" is written.  That way you can play a "4" on the B and don't need to change strings for two notes (what's that last A supposed to be?  Another "4", making for a lonely "B" on the A string, or "0" making for a two note phrase on the A string?).
As a note aside: it would appear that this is sort of a partitura (since "Violin" is marked and other instruments apparently follow below) which makes it a bit unusual that fingering indications are printed at all.
But a bass figure this clearly ain't.
Answer: Those just look like fingering indications, but yes that rhythm only makes sense if it is triplets. Sometimes they go un-notated.


Integration of $\int_{}^{}\frac{1}{x(1+x)^3}dx $

Question: we got this integration problem
$$\int_{}^{}\frac{1}{x(1+x)^3}dx $$
it seems a fairly simple problem but what i am struggling with it is doing its partital fractions
$\int_{}^{}\frac{1}{x(1+x)^3}dx $ =$\int_{}^{}\frac{a}{x}dx$ +$\int_{}^{}\frac{b}{(1+x)^3}dx$+
$\int_{}^{}\frac{c}{(1+x)^2}dx$ + $\int_{}^{}\frac{d}{1+x}dx$ now how to get values of $a,b,c,d$ ? it seems confusion by doing it by $a(1+x)^3+$ $bx+$ $cx(1+x)$ $+d(x(1+x)^2) =1$ is there any other way to break it into partial fractions and solve it ?
Comment: You are using the correct approach. What is it exactly that seems to confuse you about this method?
Comment: finding vales of a,b,c,d
Comment: Just expand everything out, then, since the right-hand-side equals 1, you know that the coefficients of $x^3, x^2$ and $x$ must be zero and the constant terms must add up to one.
Comment: e.g. if $(a+b)x^3+cx^2+(a+d)x+a+b+c=1$ then you can assert that $a+b=0, c=0, a+d=0, a+b+c=1$
Comment: Use [Maple](http://www.maplesoft.com/support/help/Maple/view.aspx?path=examples/Calculus1SingleStepping) to this end, especially the [parfrac](http://www.maplesoft.com/support/help/Maple/view.aspx?path=convert/parfrac) command. In your case $$convert(1/(x*(1+x)^3), parfrac, x) $$ produces $$x^{-1}- \left( 1+x \right) ^{-3}- \left( 1+x \right) ^{-1}- \left( 1
+x \right) ^{-2}
 $$
Comment: @user64494 While immensely functional and probably what most mathematicians would do for a 'professional' approach, for educational purposes not only is it best to learn to find the coefficients oneself, but the assignment likely requires it.
Answer: $$\frac1{x(x+1)^3}=\frac Ax+\frac B{x+1}+\frac C{(x+1)^2}+\frac D{(x+1)^3}\implies$$
$$1=A(x+1)^3+Bx(x+1)^2+Cx(x+1)+Dx$$
The above last expression is a polynomial identity and thus it is true for any value of $\;x\;$ , so substituting for example:
$$x=0\implies 1=A\cdot 1^3+0+0+0\implies A=1\\
x=-1\implies 1=0+0+0-D\implies D=-1$$
Now compare coefficients of corresponding powers of $\;x\;$ :
$$x^3\;\;\implies\;\;0=A+B\implies B=-A=-1\\x^2\;\;\implies\;\;0=3A+2B+C\implies C=-3+2=-1$$
Now check that what we got is correct...
Comment: It's worth pointing out that even though the original function is not defined at $x = 0, -1$, the polynomial identity holds for all $x \in \mathbb{R}$. That is why we are allowed to choose $x= 0$ and $x = -1$ in order to determine the coefficients. The reason why these are useful choices is that some of the terms become zero; that's also why the original function is undefined there, because these terms appear in the denominator.
Comment: Note, once you have $A,D$, you can just subtract: $$\frac{1}{x(x+1)^3} -\frac{A}{x} - \frac{D}{(x+1)^3} = \frac {B(x+1)+C}{(x+1)^2}$$
Answer: You need to begin with the good partial fraction decomposition! That is,
$$
\frac 1{x(1+x)^3} = \frac ax + \frac b{(1+x)} + \frac c{(1+x)^2} + \frac d{(1+x)^3}.
$$
This is the correct way because the partial fraction decomposition works when you put irreducible factors individually in their separate fractions, together with $k$ terms if the irreducible factor appears to the $k^{\text{th}}$ power, each term being a different power of that irreducible factor. For instance, since $(1+x)^3$ is the irreducible factor $(1+x)$ (to the third power) of $x(1+x)^3$, it must appear three times, once for each power of $(1+x)$.
This gives you the equation $a(1+x)^3 + bx(1+x)^2 + cx(1+x) + dx = 1$. Expand the factors. You'll get
$$
a + (3a + b + c + d)x + (3a + 2b + c)x^2 + (a + b) x^3 = 1.
$$
By comparing the two polynomials' coefficients, it is straightforward that $a=1$ and $b = -a = -1$. Therefore $0 = 3a + 2b + c = 3 - 2 + c = 1+c$, hence $c=-1$ and $0 = 3a + b + c + d = 3 - 1 - 1 + d = 1+d$, hence $d = -1$. This gives you
$$
\frac 1{x(1+x)^3} = \frac 1x + \frac {-1}{(1+x)} + \frac {-1}{(1+x)^2} + \frac {-1}{(1+x)^3}.
$$
Hope that helps,
Answer: Ok, your equation is right:
$$a(1 + x)^3 + bx + cx(1 + x) + d(1 + x)^2 = 1$$
Rewriting this:
$$\begin{align}
a(1 + 3x + 3x^2 + x^3) + bx + cx + cx^2 + dx(1 + 2x + x^2) & = 1 \\
a + 3ax + 3ax^2 + ax^3 + bx + cx+cx^2+dx+2dx^2+dx^3& = 1 \\
\end{align}$$
Grouping the terms by the powers of x:
$$\begin{align}
(a+d)x^3 + (3a+2d+c)x^2 + (3a+b+c+d)x + a = 1
\end{align}$$
Now as you can see, there are no $x^3, x^2, $ or $x$ terms on the right side of the equation. Therefore because the RHS (right hand side) has to equal the LHS (left hand side), we can make a system of equations for $a, b, c$ and $d$
$$\begin{align}
x^3: a +d= 0 \\
x^2: 3a + 2d+c = 0 \\
x : 3a+b+c+2d = 0 \\
Constants: a = 1
\end{align}$$
Solving this we get $a = 1,$ $b = -1,$ $c = -1,$ $d = -1$
So the partial fraction decomposition is equal to:
$$\frac{-1}{(1+x)^3} + \frac{-1}{(1+x)^2} + \frac{1}{x} + \frac{-1}{(1+x)}$$
The rest you can integrate.
Comment: is't there shorter method to do this ?
Comment: Sadly no. Partial fractions are the easiest way to do this.
Comment: Shouldn't it be $d(1+x)^2x$?
Answer: Generalization:
$$I_n=\int\frac{dx}{x(1+x)^n}=\int\frac{(1+x-x)dx}{x(1+x)^n}=\int\frac{dx}{x(1+x)^{n-1}}-\int\frac{dx}{(1+x)^n}$$
Now using this,
$$ \int\frac{dx}{(1+x)^n}=\int\frac{d(1+x)}{(1+x)^n}=\begin{cases} \ln|1+x| &\mbox{if } n=-1 \\
-\frac1{(n-1)(1+x)^{n-1}} & \text{ elsewhere } \end{cases} $$
$$\implies I_n=I_{n-1}-\begin{cases} \ln|1+x| &\mbox{if } n=-1 \\
-\frac1{(n-1)(1+x)^{n-1}} & \text{ elsewhere} \end{cases}$$
and  $\displaystyle I_0=\int\frac{dx}x=\ln|x|+C$
Here we have $n=3$


Granting restricted permission roles

Question: As well as the three standard roles for a D7 site, I have created a role for a lesser admin / content creator.  This role is essentially an administrator role with some of the juicy bits taken away.
I would like that users assigned this role can manage other users, but I need to restrict it so that they cannot assign or remove the administrator role, or edit an administrator's profile and account.  I can't see a way to do that on the standard installation, is there a module that could help me?
Edit:
I have looked into the userprotect module.  While it does prevent a lesser admin from editing an administrator, it does not prevent them from granting the administrator role on themselves.
Answer: As you mentioned, User protect should work well. Combine this with Role Delegation to restrict what roles they can assign.
Might also be worth keeping an eye on the Administer Users by Role module, although there is no D7 port yet (in progress here).
Let me know how it turns out as I'm going to be solving this issue on the site I'm working on soon.
Comment: The combination of User Protect and Role Delegation works perfectly. My lesser admins are given the Administer Users permission, but then RD controls which roles they can assign to a user and UP blocks the capability to edit any full admin's account.

Granting restricted permission roles


Existance of certain derivations on the Temperley-Lieb algebra:

Question: Given a formal parameter $\delta$ recall that the Temperley-Lieb algebra $\mathrm{TL}_n(\delta)$ is the unital $\Bbb{C}(\delta)$-algebra generated by
symbols $U_1, \dots, U_{n-1}$ subject to the (defining) relations:
\begin{equation}
\begin{array}{l}
U_i^2 = \delta U_i \\
U_i U_{i \pm 1} U_i = U_i \\
U_i U_j = U_j U_i \quad \text{for} \quad \big|\, i - j \, \big| > 1
\end{array}
\end{equation}
Question: View $\mathrm{TL}_n(\delta)$ as an infinite-dimension
$\Bbb{C}$-algebra. Does there exist a $\Bbb{C}$-algebra derivation
$D: \mathrm{TL}_n(\delta) \longrightarrow \mathrm{TL}_n(\delta)$ such
that $D$ and ${d \over {d\delta}}$ coincide upon restriction to the central $\Bbb{C}$-subalgebra $\Bbb{C}(\delta) \subset \mathrm{TL}_n(\delta)$ ?
Remark: The answer seems to be YES for $\mathrm{TL}_{\,3}(\delta)$.
An example of such a derivation is realised by setting
\begin{equation}
\begin{array}{ll}
D U_1 &\displaystyle = \ {1 \over  {1 - \delta^2}} \ U_1 U_2 \, + \, {\delta \over {\delta^2 -1}} \ U_1 \\
D U_2 & \displaystyle = \ {1 \over  {1 - \delta^2}} \ U_2 U_1 \, + \, {\delta \over {\delta^2 -1}} \ U_2 \\
\displaystyle D f &\displaystyle = \ { df \over {d \delta}} \quad \text{for all $f \in \Bbb{C}(\delta)$ }
\end{array}
\end{equation}
and extending by the (non-commutivative) Leibnitz rule. For $\text{TL}_{\, 3}(\delta)$ derivations of this kind are parametrised by a choice of $\tau \in \Bbb{C}(\delta)$; the choice in the example is $\tau = {\delta \over {\delta^2 - 1}}$.
best, Ines.
Answer: Too long for a comment, but I did a calculation and there is actually a 3 parameter family of derivations for $TL_3(\delta)$ (unless I made a mistake).
$$\begin{align}
D U_1 &= \left( \frac{\delta}{\delta^2-1}+\alpha\right)U_1-\beta\left(\frac{1}{\delta^2-1}+\alpha\delta\right)U_1U_2-(1-\beta)\left(\frac{1}{\delta^2-1}+\alpha\delta\right)U_2U_1 \\
D U_2 &= \left( \frac{\delta}{\delta^2-1}-\alpha\right)U_2-\gamma\left(\frac{1}{\delta^2-1}-\alpha\delta\right)U_1U_2-(1-\gamma)\left(\frac{1}{\delta^2-1}-\alpha\delta\right)U_2U_1
\end{align}$$
Your example corresponds to $\alpha=0, \beta=1, \gamma=0$, but one can take any $\alpha,\beta,\gamma\in \mathbb C(\delta)$.
I have thoughts on how one might organize the computation for higher $n$, but unfortunately I am not familiar enough with these algebras to know if these computations can be fully carried out.