Trouble minimizing perplexity in LDA

Question: I am running LDA from Mark Steyver's MATLAB Topic Modelling toolkit on a few Apache Java open source projects. I have taken care of stop word removal (for e.g. words such Apache, java keywords are marked as stopwords) and tokenization. I find that perplexity on test data always decreases with increasing number of topics. I tried different values of ALPHA but no difference.
I need to find optimal number of topics and for that perplexity plot should reach a minimum. Please suggest what may be wrong.
Definition and details regarding calculation of perplexity of a topic model is explained in this post.
Edit: I played with hyperparameters alpha and beta and now perplexity seems to reach a minimum. It is not clear to me as to how these hyperparameters affect perplexity. Initially I was plotting results till 200 topics without any success. Now on the same range minimum is reached at around 50-60 topics (which was my intuition) after modifying hyperparameters.
Also, as this post notes, you bias optimal number of topics according to specific values of hyperparameters.
Comment: Many of us probably don't know what perplexity means and what aperplexity plot shows.  I know I don't.  Could you enlighten me (us)?
Comment: @MichaelChernick: I edited post to include a link detailing perplexity of a topic model.
Comment: @Nick: Indeep HDP, a nonparametric topic modelling algorithm is an alternative to LDA, wherein you don't have to tune hyperparameters. However at this point I would like to stick to LDA and know how and why perplexity behaviour changes drastically with regards to small adjustments in hyperparameters.

Also, my corpus size is quite large. For e.g. I have tokenized Apache Lucene source code with ~1800 java files and 367K source code lines. So that's a pretty big corpus I guess.
Comment: How many topics have you tried so far (on what size corpus)? Maybe you just haven't yet hit the right number of topics? Also, for inferring the number of topics from data you may want to look into the Hierarchical Dirichlet Process (HDP) with code on David Blei's site: http://www.cs.princeton.edu/~blei/topicmodeling.html
Answer: You might want to have a look at the implementation of LDA in Mallet, which can do hyperparameter optimization as part of the training. Mallet also uses asymmetric priors by default, which according to this paper, leads to the model being much more robust against setting the number of topics too high. In practice this means you don't have to specify the hyperparameters, and can set number of topics pretty high without negatively affecting results.
In my experience hyperparameter optimization and asymmetric priors gave significantly better topics than without it, but I haven't tried the Matlab Topic Modelling toolkit.
Comment: Thanks for your answer. I'll try Mallet library. The MATLAB Topic Modelling toolkit doesn't allow setting asymmetric priors, although it should not be difficult to modify it's source code for that.

Trouble minimizing perplexity in LDA


How do you prove the sum of monotone sequences is also monotone?

Question: How do you prove the sum of two monotone sequences is also monotone?
Here is my thought process:
Let $a_n$ and $b_n$ be two monotone increasing sequences. Then $\forall n \in N$, $a_n \leq a_{n+1}$ and $b_n \leq b_{n+1}$. Adding both inequalities you get $a_n + b_n \leq a_{n+1} + b_{n+1}$.  Therefore in this specific case of both sequences being monotone increasing I have proven their sum is monotone increasing, and so it is also monotone.
But I'm having trouble figuring out how to apply similar logic for an $a_n$ is monotone increasing but $b_n$ is monotone decreasing.  I also tried to do proof by contradiction (like supposing the sum is not monotone), but that also lead to nowhere.
How do I prove the other cases?
Comment: You can't, as this is false.
Answer: The result is not true when $a_n$ is monotone increasing and $b_n$ is monotone decreasing.
For example,
$$a_n = 0, +1, +1, +2, +2, +3, +3, +4, +4, +5, +5, \dots$$
$$b_n = 0, \ \  0, -1, -1, -2, -2, -3, -3, -4, -4, -5, \dots $$
gives
$$ a_n + b_n = 0, +1, \ \  0, +1, \ \  0, +1, \ \  0, +1, \ \ 0, +1, \ \ 0, \dots$$
Answer: Consider the sequences defined by :
$$a_n=3n+(-1)^n$$
and
$$b_n=-2n$$
It is readily seen that $(a_n)$ is increasing, since for all $n\in\mathbb{N}$ : $a_{n+1}-a_n=3+2(-1)^{n+1}>0.$
Obviously, $(b_n)$ is decreasing.
And finally $(a_n+b_n)$ is known to be non monotonic.


In the windows if I want windows name (like:"Microsoft Windows 8 Enterprise") not like: ({Microsoft Windows NT 6.2.9200.0) using Environment?

Question: I tried to get the windows name by using System.Environment.OSVersion but it gives name like Microsoft Windows NT 6.2.9200.0 but i want the name like Microsoft Windows 8 Enterprise.Please suggest how can use the "Environment" by which i get the answer
Answer: Based on the linked SO question, you can use Get-WmiObject in PowerShell to use the Win32_OperatingSystem class.
Ex:
PS C:\Users\Louis> (Get-WmiObject Win32_OperatingSystem).Caption
Microsoft Windows 8.1 Pro with Media Center

You can also use WMI from C#:
using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("root\\CIMV2",
                    "SELECT * FROM Win32_OperatingSystem");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Win32_OperatingSystem instance");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Caption: {0}", queryObj["Caption"]);
                }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}

Comment: @user266752 I've added a C# demo.
Comment: can u please tell step by step to add this
Answer: As a c# person I grit my teeth, reference Microsoft.VisualBasic dll and...
string os = new Microsoft.VisualBasic.Devices.ComputerInfo().OSFullName.ToString();

A couple of examples from our logging app (with what System.Environment.OSVersion returns)
Microsoft Windows 8.1 Pro
(vs. Microsoft Windows NT 6.2.9200.0)
Microsoft Windows 7 Enterprise
(vs. Microsoft Windows NT 6.1.7600.0)
Microsoft Windows 7 Professional
(vs. Microsoft Windows NT 6.1.7601 Service Pack 1)
Microsoft Windows XP Professional
(vs. Microsoft Windows NT 5.1.2600 Service Pack 3)
Answer: there is no buildin way. You must use the GetProductInfo to see which SKU you use and manually write the string.


How do I choose which module to use when there are several options for the same functionality?

Question: It's not at all uncommon to find multiple modules that provide basically the same functionality. For instance, there are many SPAM control modules that offer extremely similar functionality (e.g., Spamicide and Hidden CAPTCHA). And there are lots of Taxonomy modules that do similar things. So when multiple modules meet my requirements, how should I choose which one to use?
Answer: Personally I do a few basic checks before digging deeper.

How many reported installs? (about the same in your example modules).
How long since last update to module? (Spamicide is 5 days ago (from today))
How many open issues?
Who is the developer? (Have they worked on other modules that I use, etc).

Then you can start digging into integration, if I where looking for an inline image management tool I personally would choose something that takes advantage of other modules instead of rolling it's own solutions, something that is features exportable, etc.
Comment: Great list. The only thing I would add is looking at the documentation (if any even exists). When faced with two seemingly identical modules I'll choose the one with better documentation every time.
Answer: There are comparison pages for some modules.
Information can sometimes be found googling site:groups.drupal.org and the module names.
Generic module comparison search on g.d.o
Answer: I check the number of installs, the number of developers.
Then I'll look through the open issues/bugs and use my judgement to decide if I'd ship a problem with those issues.  The responses to issues by the developers are very important to me in this process.
The number of open issues is misleading because all too often the issues aren't actually issues at all.
Finally I'll probably look at the source;
I also won't touch anything that doesn't or isn't going to have a D7 version. This may be a crude unfair metric, but it works for me, sofar... Open to persuasion that I'm wrong about this one.
Answer: Generally, in addition to the number of installs, how quickly after a new release of Drupal does this module get updated. This tells me how quick the devs are, and that also tells me how quick they will be to address any serious issue.


Per instance settings on blocks with context?

Question: Blocks normally have a single global configuration.
What options are there to provide "per instance" settings on blocks, so that I can vary them depending on where they are displayed, when they are handled with Context?
Answer: If you use Context module for block positioning - you don't need to make any changes at /admin/structure/block page.
All configuration are done in context /admin/structure/context
If you need to display the same block on different places/pages/regions - just create different context for each condition.
Comment: But that's not what I'm asking about. I'm wondering about the settings _on_ the block, as handled by [hook_block_configure](http://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_configure/7).
Comment: Sorry, I don't follow. How does this allow me to change configurations? Can I somehow set block config within Context, and I'm just missing that?
Comment: While creating context - you can specify different conditions (such as user roles, urls) and also select region where block will be displayed.
Comment: Aha, i see. i don't see such settings in context.
Answer: it's not good answer but it's fair work around for now !
implement

Implements hook_preprocess_block

help to overwrite some values
also i use value from request like $_GET['q']
i hope to see another answer


Client-Server Architectural Decision

Question: This is less of a troubleshooting question and more of an industry standards question.
I am at a crossroads where architectural standards need to be addressed and implemented.  One of these standards involves the communication route between the client application (AngularJS based, so single-page persistent with multiple views) and third party sources of information.
To me, it seems intuitive and logical to route all requests for third party libraries and data through my backend and then off to various destinations via CURL.
In this way, my server acts as a gateway between the client and the outside world (much like the relationship between a cellphone tower router and a cellphone).
I am curious as to what industry standards would say about this, and the potential pitfalls. To me, it seems like it would create more order, organization, and security long term.
Please let me know what your thoughts are regarding this, as I need outside perspectives.
Comment: What kind of application is it? Is it a data streaming application? Do you need any kind of elaboration of those data / [ETL](http://en.wikipedia.org/wiki/Extract,_transform,_load)?
Comment: B2B, no data streams.  Everything is async and session based.
Answer: Not really sure if this counts, as I am not aware of any industry standards - but I interpret it as what you're really asking for is general outside perspective. So here goes:
My short answer is that I think you're on the right track.
I think it's cleaner as it keeps the data path simple in that your client always sends requests to your server - so basically you're getting very loose coupling between your client and everything else (except towards the controller on the server, which is fine, even necessary IMO). Want to change the data source later? Client isn't affected (unless the format differs of course). It's also beneficial if you can picture yourself wanting to store the raw data in a DB for some reason some time in the future. Depending on what services you're connecting to and what you want to do with the data, going through your own server can have security benefits (like if you need to use a private key for authentication against the 3rd party service, like one has to with APIs like those MasterCard offer).
There is a performance hit though, as it gives your server more to do and requires a bit more memory, in addition to the extra requests and DNS look-ups incurred. Then again, you would be in control of caching, so you could possibly make the service slightly more robust in some cases.
So unless performance is paramount, I would go the route you were thinking of. Exactly how the routing is done on your server is a different question and might require some testing. Just make sure you use a method that lets you elegantly handle any errors that might pop up :)

Client-Server Architectural Decision


How can I allow multiple users to access/edit a microsoft access database?

Question: Now I know right off the bat that Microsoft access isn't the ideal client for multiple users accessing it but it's the only one I've got right now. I have built a small program as a sort of inventory management system. There are currently three users that will be using it regularly and at the same time. One issue I am running into with this is that sometimes the database will not be accessible and will give an error stating that the file is already in use by "so and so" user. The other issue is that I'm getting a similar error every now and then where it states "The database has been placed in a state by user  on machine  that prevents it from being opened or locked". I am connecting to the database through an ACE OLEDB connection using the line below
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"

I have also changed some of the settings in the actual access database such as:

Enable all macros
Add the folder the database is in to the trusted locations list
Confirm that the database is set to open in shared mode by default

I don't know if there is something small I've missed or a setting I need to change but as of yet, the problem is still persisting.
Below is an example of how I am using the database. I am using string based SQL commands but am not too familiar with DataSet/DataTable/etc. items, so I may be doing something incorrectly.
 'close connection from any previous session
    con.Close()

    'clear dataset so as not to append data
    ds.Clear()

    'Select SQL query that selects ALL records from a table
    Dim str As String = "SELECT * FROM " & "[" & table & "]" & ""
    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"

    'use try catch statement to open the connection
    Try
        con.Open()
    Catch ex As Exception
        MsgBox(Convert.ToString(ex))
    End Try

    'use try catch statement to add a table (dt) to the dataset (ds) in order to store values
    Try
        ds.Tables.Add(dt)
    Catch ex As Exception

    End Try

    'create new dataadapter object using the sql string from above and the connection created above
    da = New OleDbDataAdapter(str, con)

    'create new command builder in order to excecute the SELECT SQL statement using the dataadapter created (da)
    'specify prefix and suffix for cb
    Dim cb = New OleDbCommandBuilder(da) With {
        .QuotePrefix = "[",
        .QuoteSuffix = "]"
    }

    'use try catch statement to fill the datatable (dt) using the dataadapter (da)
    Try
        da.Fill(dt)
    Catch ex As Exception
        MsgBox(Convert.ToString(ex))
    End Try

    'set the datasource of the datagridview to the datatable
    dgv.DataSource = dt.DefaultView

    'close the connection to the database
    con.Close()

Comment: The `sometimes the database will not be accessible` really hints that someone is probably opening the database in exclusive mode through the Access program.
Comment: Are there users that are opening the database directly, or is it just through your program?
Comment: How are you accessing the data?  Show an example.  My experience with MS Access through .Net is never use Access Queries — always call your sql string directly.
Comment: @ErikvonAsmuth The users are only accessing the database through the program. I do open the database every now and then to check on the data and gather information.
Comment: @LarsTech I am using string based sql queries to do all of my select/update/insert functions. Ill add an example at the end of my question
Comment: You need to make sure you do things like dispose of connections and datareaders in the smallest scope possible - the code shown doesnt.  Also probably bundle updates into small groups so that the DB is never tied up any longer than needed.  And then you open the file, do it without exclusive access.
Comment: @LarsTech That may be true, I am the only one that has access installed on their computer so it would have to be me. Is there a way to make sure it does not open in exclusive mode other than changing the default opening setting to shared?
Comment: @Plutonix That makes sense. Would you be able to elaborate on what you mean by that? Would I just be able to add more con.open() and con.close() lines to achieve that or do you recommend i rewrite some of my code? As of right now this is the only way i know how to open and manipulate a database
Comment: I'm trying to be helpful by saying this...your comments should gear more toward the why and the bigger picture of the purpose of the code. The comments you have are describing what the code is currently doing. It's like reading a comment and then reading the comment again, but in code.
Comment: @MichaelZ. Understandable! Writing comments are kind of a new thing for me so I have a bad habit of making them too simple or redundant just to get it over with. Thanks for the suggestion!
Answer: Go to your Back-End Access DB file. File > Options > Client Settings. For your Use Case No Locks should be fine, but Edited record setting will work as well if you need it
Comment: I had not heard of splitting a database before this. It sounds like it could help the strain of multiple users on the database. Ill try to split it and see how that works. Would i need to change anything in the VB side of things in terms of how I am referencing the database or getting information from it?
Comment: I believe that you had mentioned in the comments above that you are referencing the DB through a program. I removed the section in my answer containing that information. Are you using an Access Form to interact with the DB? or are you using your own program?
Comment: I am using my own program to interact with the database. I have split the database and restarted the program but it is still giving me the same errors as before
Comment: Splitting the database will be of no use to you then. Splitting is for when you are using Access forms to interact with the DB
Comment: Oh alright I see, thank you for trying to help anyways! Is there anything else you can think of that might help?
Comment: Have you tried my edited answer? This is still relevant for your use case
Comment: Yes, I've tried setting the default record locking to both no locks and edited record. Neither of them has worked
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148539/discussion-between-chance-finley-and-nickhallick).
Answer:
but its [sic] the only one I've got right now

Actually, it's not.
Have a look at SQL Server Compact. It's free, it's small and it handles multiple users with aplomb.
You can add all the references you need using NuGet.


Constructing Scores for Machine Learned Ranking on a Labeled Dataset with Classifiers and Regressors

Question: I have a dataset containing students test grades on different classes and personal information, as well as a label from the set {'abandoned college', 'graduated', 'master', 'phd'} which describes how far that student went on his academic life.
My goal was to generate a continuous score that is directly proportional to how far one student is likely to reach on his academic life. (e.g. on a 0-10 scale, a 1 student is unlikely to go to masters and a 9 student is very likely to go reach PhD).
(This idea was to compare this new metric with the GPA)
My initial approach was to solve this as a classification problem and use the classifier built in probabilities estimators as a score. But because it's a multiclass label, I end up with multiple probabilities. Also, those probabilities frequently are very sparse values.
Because the labels have an ordering, I thought of using a Regression instead, and just scale the predicted value. But, even though that works numerically I'm not sure it makes sense theoretically.
Is my goal even reachable, or is my problem ill defined? I've seen similar questions mentioning Ordered Regression, but I think it would not be enough (just better than ordinary classification).
Should I combine Classification and Regression or just pick one?
UPDATE
As suggested by a friend, I tried ensemble stacking. In a first layer I use two classifiers and in the second layer, a Regressor. This made no significant difference in the output (although it could be bad execution from my part) and I think that it makes a little bit more sense theoreticaly - the regressor is learning how to balance each classifier's opinion.
UPDATE2
It looks like L2R would be my best bet, but there's still a problem of missing data. Because each student has taken different classes, the only way to compare them directly would be to generate standard features commonly available. So the problem also imposes a problem of classification with missing features, which is hard on its own merit.
Answer: As you have already mentioned, your response variable is ordinal. So it makes sense to try a classifier that can handle this type of variables. For example, Frank and Hall [1) proposed a simple to implement ordinal classifier. Their approach can be adapted to almost any type of classifier however, if the number of classes is low you might not get an accuracy improvement compared with a traditional classifier as stated by the authors and also empirically tested in [2].
Also, be aware that since you are dealing with an ordinal classification problem, standard performance metrics may not be informative of the classification error since they are designed for unordered classes. These metrics treat all errors as equal. For example, confusing abandoned college with phd is more severe than confusing master with phd.  For this reason, you may want to use additional performance metrics such as mean squared error, mean absolute error, linear correlation, accuracy within n [3].
You may also be interested in Learning to Rank algorithms.
1- E. Frank and M. Hall, "A simple approach to ordinal classification," in 636 Proc. 12th Eur. Conf. Mach. Learning, 2001, vol. 2167, pp. 145–156. 637 [40] L. Gaudette and N. Japkowicz, "Evaluation methods for ordinal classifi- 638
cation," Adv. Artif. Intell., vol. 5549, pp. 207–210, 2009.
2- Automatic Stress Detection in Working Environments from Smartphones' Accelerometer Data: A First Step. Garcia-Ceja, E., Venet Osmani, Oscar Mayora. Biomedical and Health Informatics, IEEE Journal of,  vol. 20, no. 4, pp. 1053-1060, July 2016.
3- L. Gaudette and N. Japkowicz, "Evaluation methods for ordinal classification" Adv. Artif. Intell., vol. 5549, pp. 207–210, 2009.
Comment: I'll accept you answer, even though I wished a little bit more. I'm now looking into L2R with neural networks and will create another answer if I happen to find something worthy of sharing.
Comment: Thanks for the references. The approach on [1] did make an improvement, and although [3] was not very useful I ended up finding related papers that were.


How to locate page template in use?

Question: I have a strange situation where my Drupal 7 Omega 4 site appears to not be using a page.tpl.php template. The page renders and content appears but when I alter all of my page templates to indicate which one is in use (By adding a "
TEMPLATE NAME.tpl.php
 above the "print render($page['content']);") I see nothing in the rendered output on screen.
I have cleared the caches. Many times.
Is it possible for Drupal to somehow not use a page template and still render a page's content? I would have thought not but can't figure out how this could be happening.
I'm guessing I'm completely forgetting something quite basic here.
Any help greatly appreciated.
Answer: You can use the https://www.drupal.org/project/devel_themer module to see what tpl file is in use. You should see the path to your subtheme. If you see the path to the base theme, then your tpl file is not found.
Comment: Thanks for this tip. It worked a treat but showed up that for some reason my theme is using the Omega simple layout. I'll have to figure out why that's happening now :)
Comment: @dibs Go into the theme settings for your active theme, and select the Layouts tab.  Uncheck "Enable layouts extension" and you should get your normal page template back.
Comment: @MPD Strangely the layouts switch does nothing. I just get the omega simple layout either way. However once I use THEME_omega_layout_alter() I can control which layout I get. Something seems a bit odd but at least it's working for me now.
Comment: @dibs If you are loading theme settings from a file, you may need to update there.
Answer: There are quite a few variables that determine which template/function is used for any specific theme hook. There is a hierarchy of suggestions involved, where different patterns may take precedence. That general concept is outlined in the main theme documentation.
It's also important to note that if you are using a sub-theme (as is likely the case with a framework like Omega) your sub-theme's "page" template will take precedence over Omega's "page" template, which will also have precedence over core's own "page" template.
Because of all these precedence rules, you may have a case where there is a page template defined in your setup, which you have not "tagged" with your test
TEMPLATE NAME.tpl.php
 text, that is being selected by specificity (perhaps it's targeting a content type, or path, or something more specific than the generic page templates you have already checked).
To see exactly which templates are used at any given time, you may want to check out the Theme Develper module, as it will provide a nice visual explanation of how Drupal's various theme hooks are related to DOM elements. Here's an example of the kind of output it can produce for the page-level container:
Comment: Ha, it looks like a bunch of people posted simultaneously with essentially the same answer (use Theme Developer module). Anyway, I tried to add some additional notes in the answer above to explain some of the variables involved in the selection process. Maybe that will help others.
Answer: Check out Theme Developer. It will show you what templates are used on each renderable part of the page (page, block, node, etc.).
You could probably also implement hook_preprocess_page in your custom theme, and look at either $vars['theme_hook_suggestions'] or $vars['theme_hook_suggestion']. See this page about template suggestions.

How to locate page template in use?


Error running while executing "docker exec" on running containers

Question: I have been trying to execute below commands on my running container but every time I execute any command it gives me an error. The image is for windows containers
docker exec "Container name" cat /etc/hosts
docker exec "Container name" bash
docker exec "Container name" sh

this is the error I get
container 765e4e8d647d54051c1926e591666b87d1e6e95187920f9e42f6b62b97ff508e encountered an error during hcsshim::System::CreateProcess: failure in a Windows system call: The system cannot find the file specified. (0x2)
[Event Detail:  Provider: 00000000-0000-0000-0000-000000000000]
[Event Detail:  Provider: 00000000-0000-0000-0000-000000000000]
[Event Detail: onecore\vm\compute\management\orchestration\vmhostedcontainer\processmanagement.cpp(173)\vmcomputeagent.exe!00007FF6B747AE77: (caller: 00007FF6B742E4AB) Exception(3) tid(798) 80070002 The system cannot find the file specified.
    CallContext:[\Bridge_ProcessMessage\VmHostedContainer_ExecuteProcess]
 Provider: 00000000-0000-0000-0000-000000000000] extra info: {"CommandLine":"cat /etc/host","WorkingDirectory":"/","Environment":{"COMPLUS_NGenProtectedProcess_FeatureEnabled":"0","DOTNET_RUNNING_IN_CONTAINER":"true","ROSLYN_COMPILER_LOCATION":"c:\\RoslynCompilers\\tools"},"CreateStdInPipe":true,"CreateStdOutPipe":true,"CreateStdErrPipe":true,"ConsoleSize":[0,0]}
PS C:\windows\system32> docker exec angry_pascal cat /etc/host
container 765e4e8d647d54051c1926e591666b87d1e6e95187920f9e42f6b62b97ff508e encountered an error during hcsshim::System::CreateProcess: failure in a Windows system call: The system cannot find the file specified. (0x2)
[Event Detail:  Provider: 00000000-0000-0000-0000-000000000000]
[Event Detail:  Provider: 00000000-0000-0000-0000-000000000000]
[Event Detail: onecore\vm\compute\management\orchestration\vmhostedcontainer\processmanagement.cpp(173)\vmcomputeagent.exe!00007FF6B747AE77: (caller: 00007FF6B742E4AB) Exception(4) tid(638) 80070002 The system cannot find the file specified.
    CallContext:[\Bridge_ProcessMessage\VmHostedContainer_ExecuteProcess]
 Provider: 00000000-0000-0000-0000-000000000000] extra info: {"CommandLine":"cat /etc/host","WorkingDirectory":"/","Environment":{"COMPLUS_NGenProtectedProcess_FeatureEnabled":"0","DOTNET_RUNNING_IN_CONTAINER":"true","ROSLYN_COMPILER_LOCATION":"c:\\RoslynCompilers\\tools"},"CreateStdInPipe":true,"CreateStdOutPipe":true,"CreateStdErrPipe":true,"ConsoleSize":[0,0]}

I went through docker documentation and some Github forums as well but I couldn't find a solution to it. Below is my docker file
FROM microsoft/aspnet
COPY ./bin/Release/PublishOutput .

Its a very basic docker file, so I am not sure if I am missing something or I am doing something wrong. Any help on this would be appreciated. Cheers!
Answer: I'm pretty sure /etc/host file won't be inside container because you're missing last s.
Also I don't know much about Windows containers but my wild guess would be that linux binaries such as sh, bash or cat are not available in Windows. Instead you should invoke powershell.exe for example as described here:
https://www.ntweekly.com/2019/09/20/how-to-attach-to-a-running-windows-container/
Comment: I edited the answer.. Windows use different filesystem structure so I'd say hosts file is somewhere in `C:\Windows\System32\drivers\etc\hosts` - also you must use some equivalent of cat such as `type file.txt`
Comment: So when I follow the post that you have linked I get this ```service 'w3svc' failed APPCMD failed with error code 4312 Failed to update IIS configuration ```
Answer: As mentioned by @Ordrej Bardon that I wasn't using windows commands to interact with my container and instead of using sh,bash or cat I should use powershell.exe or cmd.exe. This would solve one part of the problem but would start giving
service 'w3svc' failed
APPCMD failed with error code 4312
Failed to update IIS configuration

To solve this problem refer to Can't run microsoft/aspnet interactively. Here the solution and explanation of this problem is given
Solution :
Changes in Dockerfile
Add ENTRYPOINT["powershell"]
FROM microsoft/aspnet
ENTRYPOINT["powershell"]
COPY ./bin/Release/PublishOutput .

Explanation:

The entrypoint is defined as ENTRYPOINT ["C:\ServiceMonitor.exe", "w3svc"]. When you add cmd.exe as the run parameter, it is attempting to add that as an argument after ServiceMonitor.exe w3svc.
With that Dockerfile, you could then do docker build -t aspnet . and then run it interactively by docker run -it aspnet.


Can't connect to Team Foundation Server

Question: I've been happily using Team Foundation Server with Visual Studio 2010 for the last couple of months at my current place of work when it has suddenly stopped working. I get the following errors:

If I browse to the wiki (Sharepoint) on the TFS server it works fine in Firefox but in Internet Explorer it fails with:

No authority could be contacted for authentication.

I'm not aware of any changes to the server or my machine that would cause the errors and other users of TFS are not affected.
The TFS server is on a different domain to my machine, but usually I get prompted to login and using a domain prefixed username works. At the moment, I don't even get a login prompt anymore.
How do I fix this?
Comment: Does it respond to WS? http://tfs_server_name:8080/tfs/DefaultCollection/Services/v1.0/serverstatus.asmx
Comment: No. I tried to add a service reference in Visual Studio, but it fails with the same error. However, the Add Service Reference dialog doesn't seem to give me a way to enter credentials which I'd need to do since it is on a different domain.
Comment: After a few days the problem disappeared, only to return a few weeks later.
Answer: I have recently started to experience a similar issue. We also host TFS on a different domain.   Twice in the last week TFS has stopped authenticating users, and I have received messages similar to above. I have no idea what is causing this, but on each occasion SQL Server Agent service was stopped. A reboot of the server and a manual restart of SQL Server agent seems to fix the problem temporarily. I'm not sure if this information is helpful, but I would also really appreciate any help in getting to the bottom of this.
Answer: We used a workaround to get past this problem. We configured an entry in the Windows Stored User Names and Passwords tool for the domain of the TFS server. It got around the  problem of TFS not prompting for credentials by explicitly supplying them via this tool.

When you change your password for that domain account, you must also change the password here otherwise your account can be locked after failing authentication too many times.
Answer: I had the same problem, sorted it by upgrading to tfs2012
Answer: In my case, I changed the default port  8080 to port 80 and everything worked fine. but the message could also happen due to wrong saved credentials. you can go to the control panel of the windows and search for credentials manager and then remove your TFS credentials.
Comment: I'm not saying it didn't work for you... but this question starts with "it has suddenly stopped working". I'm not saying you are wrong... just asking questions that come to mind. For example, you could be right, it could have been a client upgrade changed the default port, and then you changed your port... and that might even the situation described in the question. (Vendors have done that... I think I worked for a couple, but thankfully I can't remember which products did that).
Comment: Based on the details provided by the question, I don't think that solves the problem in this situation. Were you getting the exact same error?(After all, some products do display very inaccurate network errors.)
Comment: My answer is an exact solution for the exact same error message. if you notice the picture in the question the port is 8080, so my answer points to the very same problem. now, why do think it is irrelevant? what is your evidence?
Comment: you are right benc, in this case, the cause of the problem could also be the wrong saved credentials . and can be solved by removing saved credential in credential manager.

Can't connect to Team Foundation Server


Selecionar valores extremos de um determinado intervalo no MySQL

Question: Preciso coletar apenas os valores extremos de 'id' para cada faixa horária dada. Conforme os dados abaixo, preciso coletar os id's 63 e 67 para a hora de 00:45:22, 80 e 84 para a hora de 01:15:26. Como proceder?
id   n  hora          data      AP

63  5   00:45:22    24/05/2017  3
64  5   00:45:22    24/05/2017  1
65  5   00:45:22    24/05/2017  3
66  5   00:45:22    24/05/2017  3
67  5   00:45:22    24/05/2017  3
80  5   01:15:26    24/05/2017  5
81  5   01:15:26    24/05/2017  5
82  5   01:15:26    24/05/2017  5
83  5   01:15:26    24/05/2017  5
84  5   01:15:26    24/05/2017  5

Comment: Sim Jefferson, preciso obter uma seleção final que me forneça os APs de cada id, tanto máximo, quanto mínimo. Entretanto, para o que perguntei a resposta do Motta é suficiente
Comment: `AP` ou `N` influencia na resposta esperada?
Answer: MAX e GROUP BY
select hora , min(id) min_id , max(id) max_id
from tabela
group by hora

O  GROUP BY é usado quando se quer usar agregadores como soma , contagem , média , desvio padrão , máximo e mínimos , pode ser usado também para a eliminação de duplicados , sempre recomendo uma leitura na documentação do fornecedor do SGBD para detalhes.
Comment: Motta, o objetivo do site é gerar conteúdo de qualidade que sirva de referência para outras pessoas, não apenas solucionar um problema particular. Então o ideal é que você coloque pelo menos a explicação mínima do que seu código faz na resposta, sem depender de links. Obviamente que é interessante você também citar a referência oficial caso a pessoa queira estender a pesquisa.
Comment: Motta, tem como explicar melhor o que cada função faz? Principalmente o `group by`. Aliás, é necessário pegar o `id` mínimo também.
Comment: http://www.devmedia.com.br/exemplos-com-group-by-e-com-a-clausula-having-totalizando-dados-sql-server-2008-parte-2/19839  veja link para uso do group by ..   O mínimo foi editado na resposta ,


Design pattern code for conditional code scattered across multiple classes

Question: Some code needs to be refactored in approx 10 classes, of these
classes there are conditionals scattered throughout the classes painting
text onto the screen where appropriate. I want to add all this code conditional/painting
code into one centralised location.
Is there a design pattern appropriate for this ?
if (fontWidth == 100) {
    fontSize = large;
} else {
    fontSize = small;
}

if (fontWidth == 100) {
    graphics.drawText("100", xVal, yVal);
} else {
    xText = Utils.calculateXText(param1, param2);
    graphics.drawText("200", xVal, yVal);
}

For delegation does it mean I need to write defferent wrapper objects, one for setting the font size and one for drawing the text based on above  code ?
public void paint(Graphics graphics){

    super.paint(graphics);
    Font font;

    if(ScreenDimension.getFontWidth() == 320){
        font = Font.getDefault().derive(Font.PLAIN,10,Ui.UNITS_pt);
    }
    else {
        font = Font.getDefault().derive(Font.PLAIN,12,Ui.UNITS_pt);
    }

String strScore = String.valueOf(score);
    graphics.setFont(font);
    int pixelWidth = font.getAdvance(strScore);

    if(ScreenDimension.getFontWidth() == 320){
        graphics.drawText(strScore, (int) (this.backgroundBitmap.getWidth() * 0.50) - (pixelWidth/2), 10);
    }
    else {
        graphics.drawText(strScore, (int) (this.backgroundBitmap.getWidth() * 0.50) - (pixelWidth/2), 20);
    }

    if(ScreenDimension.getFontWidth() == 320){
        font = Font.getDefault().derive(Font.PLAIN,6,Ui.UNITS_pt);
    }
    else {
        font = Font.getDefault().derive(Font.PLAIN,8,Ui.UNITS_pt);
    }

    int namePixelWidth = font.getAdvance(judgeName);
    graphics.setFont(font);

if(ScreenDimension.getFontWidth() == 320){
    graphics.drawText(judgeName, (int) (this.backgroundBitmap.getWidth() * 0.50) - (namePixelWidth/2), this.backgroundBitmap.getHeight() - font.getHeight() - 2);
}
    else {
        graphics.drawText(judgeName, (int) (this.backgroundBitmap.getWidth() * 0.50) - (namePixelWidth/2), this.backgroundBitmap.getHeight() - font.getHeight() - 15);
    }
}

Answer: You could use a delegate object that would inspect your 10 classes to draw the text appropriately.
You could also simply make a static helper function to execute that code (simple and easy way).
In fact it is hard to give a proper opinion without seeing more code.
Answer: You possibly want to use a Strategy pattern, defining something like
/**
 * Strategy to render some text, of two size variants, centered horizontally
 * at a specified position.
 */
public interface TextRenderer {
    public enum FontSize { LARGE, SMALL };
    public void render(String text, int x, int y, FontSize size);
}

/**
 * TextRenderer Factory that uses the ScreenDimension to determine sizes of LARGE
 * and SMALL fonts to use.
 */
public class ScreenDimensionAwareTextRendererFactory {
    public static TextRenderer getTextRenderer(Graphics gc) {
        Font baseFont = Font.getDefault();
        int fontWidth = ScreenDimension.getFontWidth();
        return fontWidth == 320
                ? new DefaultTextRenderer(gc, baseFont.derive(Font.PLAIN,10,Ui.UNITS_pt), baseFont.derive(Font.PLAIN,6,Ui.UNITS_pt))
                : new DefaultTextRenderer(gc, baseFont.derive(Font.PLAIN,12,Ui.UNITS_pt), baseFont.derive(Font.PLAIN,8,Ui.UNITS_pt));
    }
}

public class DefaultTextRenderer implements TextRenderer {
    protected Map<FontSize,Font> fontSizeMap = new HashMap<FontSize,Font>();
    protected Graphics gc;
    public DefaultTextRenderer(Graphics gc, Font largeFont, Font smallFont) {
        this.gc = gc;
        fontSizeMap.put(LARGE, largeFont);
        fontSizeMap.put(SMALL, smallFont);
    }
    public void render(String text, int x, int y, FontSize size) {
        Font font = fontSizeMap.get(size)
        int pixelWidth = font.getAdvance(text);
        gc.setFont(font);

        // TODO: note here I'm not dealing with the vertical offsets you're using
        // which are dependent upon the font size. It would be possible, but
        // I suspect what you really ought to be doing is consistently rendering
        // text on a baseline.
        // The way you could adjust this to closer match what you appear to be doing
        // would be to have arguments to render() which indicate vertical alignment.
        // something like
        // TextRenderer.VerticalAlignment = enum { BASELINE, TOP, BOTTOM }
        // and based on something like that you could compute here the y offset
        // based on the selected font.
        // I can't do that now because you're "magic numbers" hard coded don't explain
        // what they're trying to do
        gc.drawText(text, Math.round(x - (pixelWidth / 2)), y);
    }
}

// your example
public void paint(Graphics graphics) {
    super.paint(graphics);

    String strScore = String.valueOf(score);
    TextRenderer textRenderer = ScreenDimensionAwareTextRendererFactory.getTextRenderer(graphics);
    int middleX = Math.round(this.backgroundBitmap.getWidth() / 2);
    textRenderer.render(strScore, middleX, 10, TextRenderer.TextSize.LARGE);
    textRenderer.render(judgeName, middleX, this.backgroundBitmap.getHeight(), TextRenderer.TextSize.SMALL);
}

Comment: Thanks but if the graphics reference is set within the calling class should the graphics reference not be passed into the LargeTextRenderer & SmallTextRenderer classes ?
Comment: Indeed, if the use case requires that the GC is provided to the strategy implementation then so be it. Likewise if you need to be able to provide locations on the GC, they get passed in too. Without more context in you initial code sample it's not possible to know this for the answer. I'll update the code
Comment: The key to remember here is that the Strategy pattern defines a consistent interface, in this case something like "render some text at some x/y position", and implementations define how that happens, specifically here the implementations differ in how they render different sized text. This is illustrated by the fact that the different implementations main differences are focused around the font width/size.
Comment: I've added another code snippet from a different method, could the same strategy pattern you described be used in this case ?
Comment: Yes, I'll update my answer to match the extended sample you've provided
Comment: After multiple edits I think it's there. Note that the doc for the interface TextRenderer really explains what it's there to do. If you have other classes which have other expectations, such as the text not being centered horizontally, then the interface would need to be expanded to suit, much like I explained about the vertical alignment. It may need some tweaking to compile, I've not tried, but you should be able to see the general idea, and it greatly simplifies the calling code, which is the benefit of this pattern.
Comment: Thanks for this, I'll go through your code and try to implement it in the app, will take some time though, so if you don't mind I'll leave this question open, ill prob have a point or two I need clarifying when I go through it. Hopefully tomorrow.
Answer: If the conditionals don't vary, you could use the Servant design pattern.
http://en.wikipedia.org/wiki/Design_pattern_Servant


Representing a Riemannian metric in $\mathbb R^3$ restricted to the upper half of $S^2$

Question: Consider $M := \mathbb R^3$ as a smooth manifold with a Riemannian metric $g := \sum_{i=1}^3 dx^i\otimes dx^i$, where $(x^1, x^2, x^3)$ is the standard coordinate of $M$.  Let $N\subset M$ be a submanifold defined as $S^2 \cap H$, where $H = \{(x^1, x^2, x^3) \mid x^3 > 0\}$. Then $N$ has the coordinate $(x^1,x^2)$.
The problem is to represent the restriction of $g$ to the tangent bundle $TN$ w.r.t. the (global) frame $(dx^1, dx^2)$.
I tried to solve it in the following way: I introduced a coordinate neighborhood $(M \cap H , \psi)$ to $M$, where $\psi:M\cap H \rightarrow(0,\infty)\times(0,\pi)\times(0,\pi)$ is a diffeomorphism defined by $\psi^{-1}(r, \phi, \theta) = (r\cos\phi, r\sin\phi\cos\theta, r\sin\phi\sin\theta)$.  Then I write $g$ in terms of $dr$, $d\phi$ and $d\theta$. Since I get $g|_{TN^{\otimes 2}}$ by dropping the terms that involve $dr$ from $g$, I rewrite this in terms of $dx^1, dx^2$ by applying inverse mapping theorem to obtain the result.
While this seems to work in theory, it is a bit cumbersome.  I would be most grateful if you could help me solve this problem more easily.
Comment: if $x_3>0$, then you can (globally) parametrize $N$ as $N=\{(x_1,x_2,\sqrt{1-x_1^2-x_2^2})\}$ and compute the restriction of $g$ to $N$, right?
Comment: Thank you, but I am totally unfamiliar with these things, so I would appreciate if you could elaborate on that.
Answer: Let me elaborate on Avitus's comment.

Let $\iota : N \to \mathbb{R}^3$ be the canonical embedding. Then what you want to understand is actually $\iota^\ast g = \delta_{ij} \iota^\ast dx^i \otimes \iota^\ast dx^j$.
As you observed, you actually have a diffeomorphism $\phi : N \to U := \{(y^1,y^2) \in \mathbb{R}^2 \mid (y^1)^2 + (y^2)^2 < 1\}$ given by $$\phi(x^1,x^2,x^3) := (x^1,x^2),$$ so that $T^\ast N$ admits the global frame $$\{\phi^\ast dy^1,\phi^\ast dy^2\}.$$ What you would like to do is express $\iota^\ast g$ in terms of $\phi^\ast dy^1$ and $\phi^\ast dy^2$, which involves expressing $\{\iota^\ast dx^1,\iota^\ast dx^2,\iota^\ast dx^3\}$ in terms of $\{\phi^\ast dy^1,\phi^\ast dy^2\}$.
As Avitus observed, $\phi^{-1} : U \to N$ is given by
$$
\phi^{-1}(y^1,y^2) = \left(y^1,y^2,\sqrt{1-(y^1)^2-(y^2)^2}\right).
$$ You can readily check, then, that
$$
 (\iota \circ \phi^{-1})^\ast(dx^1) = dy^1, \quad (\iota \circ \phi^{-1})^\ast(dx^2) = dy^1,\\(\iota \circ \phi^{-1})^\ast(dx^3)
= -\frac{y^1}{\sqrt{1-(y^1)^2-(y^2)^2}} dy^1 -\frac{y^2}{\sqrt{1-(y^1)^2-(y^2)^2}} dy^2.
$$

Now, observe that by the basic properties of pullbacks, for any $\omega \in \Omega^1(\mathbb{R}^3)$,
$$
 \phi^\ast\left(\iota \circ \phi^{-1}\right)^\ast(\omega) = \left(\left(\iota \circ \phi^{-1}\right) \circ \phi\right)^\ast(\omega) = \iota^\ast(\omega).
$$
What does this imply, then, for $\iota^\ast dx^1$, $\iota^\ast dx^2$, $\iota^\ast dx^3$? What does this, in turn, imply for $\iota^\ast g$?
Comment: That simplified the calculation.  Thank you. How do I know that what I want to understand is $\iota^*g$?
Comment: Because that's actually how you induce a Riemannian metric on a submanifold, by pulling back via the inclusion. If you like, you can view it roughly as restricting $g$ to a section of $T^\ast \mathbb{R}^3 \otimes T^\ast \mathbb{R}^3|_N$, and then reinterpreting the result as a section of $T^\ast N \otimes T^\ast N$, which is what you actually want.
Comment: Is the definition of a metric on a submanifold by pulling back equal to the one in my first attempt to solve the problem, i.e., by dropping the terms that contain $dr$?  (The problem is that the professor did not define how to induce a metric on a submanifold...)
Comment: What you did is at least a heuristic derivation of exactly the same  induced metric $\iota^\ast g$, namely, the round metric on $S^3$, except in spherical coordinates instead of the one you were actually interested in. Rigorously, though, what you should do instead is repeat the procedure of the answer, except replacing the diffeomorphism $\phi : N \to U$ with the coordinate chart $\psi : V \to (0,2\pi) \times (0,\pi)$, where $\psi^{-1}(\phi,\theta) := (\cos \phi \sin \theta, \sin \phi \sin \theta, \cos \theta)$.
Comment: That your original derivation with spherical coordinates works out is ultimately because spherical coordinates on $\mathbb{R}^3$ and spherical coordinates on the sphere $S^3$ are compatible with the inclusions
$$
 (0,2\pi) \times (0,\pi) \hookrightarrow (0,\infty) \times (0,2\pi) \times (0,\pi), \quad (\phi,\theta) \mapsto (1,\phi,\theta),\\
S^3 \hookrightarrow \mathbb{R}^3,
$$
fitting into a nice commutative diagram.
Comment: Correction: It should be $\psi : V \to (0,2\pi) \times (0,\pi/2)$, to get just the upper hemisphere $N$.
Answer: Here is a pedestrian approach:
Denote the coordinates in $N$ by $z=(z_1,z_2)$. Then we have a map
$$f:\quad N\to {\mathbb R}^3, \qquad (z_1,z_2)\mapsto\left(z_1,z_2,\sqrt{1-z_1^2-z_2^2}\right)\ .$$
One computes
$$df(z).e_1=f_{.1}(z)=\bigl(1,0,-z_1/\sqrt{1-z_1^2-z_2^2}\bigr),\quad
df(z).e_2=f_{.2}(z)=\bigl(0,1,-z_2/\sqrt{1-z_1^2-z_2^2}\bigr)\ .\tag{1}$$
Now the fundamental form $g$ in ${\mathbb R}^3$ is just the scalar product. The matrix $\bigl[g^*_{ik}(z)\bigr]$ of the pullback $g^*$ on $N$ is therefore given by
$$\eqalign{g^*_{ik}(z)&=g^*(z).(e_i,e_k)= df(z).e_i\>\cdot\>df(z).e_k\cr &=f_{.i}(z)\cdot f_{.k}(z)\ .\cr}$$
Now plug in the expressions obtained in $(1)$ and obtain
$$\bigl[g^*_{ik}(z)\bigr]=\left[\matrix{{1-z_2^2\over 1-z_1^2-z_2^2} &{z_1z_2\over 1-z_1^2-z_2^2} \cr {z_1z_2\over 1-z_1^2-z_2^2}  & {1-z_1^2\over 1-z_1^2-z_2^2}  \cr}\right]\ .$$


How to get the exact text a user entered into a cell in excel

Question: I should start by saying that I know no VBA
I have to enter a lot of time values in excel.  Because it really slows me down entering a colon whilst typing, I thought I would write a macro that would allow me to enter a string like "18.10" and convert it to "18:10".  (Then I could just use the numpad and enter the times quickly).
I have cobbled together the function to convert any given (delimited) string into a time - that was easy.  But now I am having trouble with my event handler because I cannot get at the exact text that I enter because Excel appears to be treating it as a number and trimming trailing 0s.
E.g. 18.10 gets converted to 18.1 - which gets converted to 18:01 (and not 18:10 as I want it to).
Here is my change handling code (copied from the interweb)
    Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim TimeStr As String

' This code copied from Chip Pearson
'http://www.cpearson.com/excel/DateTimeEntry.htm
If Application.Intersect(Target, Range("C6:F1000")) Is Nothing Then
    Exit Sub
End If
If Target.Cells.Count > 1 Then
    Exit Sub
End If
If Target.Value = "" Then
    Exit Sub
End If

Application.EnableEvents = False
With Target
    TimeStr = .Text  ' What should I use here????
    If .HasFormula = False Then
        .Value = ConvertToTime(TimeStr)
    End If
End With
Application.EnableEvents = True
Exit Sub

EndMacro:
    MsgBox "You did not enter a valid time"
    Application.EnableEvents = True
    End Sub
As you can see I am currently using Text - I have looked at all the properties on Target in the debugger and could not find any that looked like it was the raw entered text.  Is there a way to get at the value?
Any help greatly appreciated.

Thank you Issun and Craig.  Issun is correct - I am making it overly complicated (w.r.t. to conversion to time).  Here is what I have come up with and works rather well.
' This requires the format of the cells to ce "0.00" to prevent trailing 0s being trimmed
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
On Error GoTo ErrHandler:

Dim TimeStr As String
Dim TimeVal
' I am only entering times in this range
If Application.Intersect(Target, Range("C6:F1000")) Is Nothing Then
    Exit Sub
End If
If Target.Cells.Count > 1 Then
    Exit Sub
End If
If Target.Value = "" Then
    Exit Sub
End If

TimeStr = Replace(Target.Text, ".", ":")
TimeVal = TimeValue(TimeStr)
Application.EnableEvents = False
Target.Value = TimeVal
Target.NumberFormat = "h:mm"
Application.EnableEvents = True

Exit Sub
ErrHandler:
Exit Sub
End Sub

Sub SetTimeFormat()
    Selection.NumberFormat = "h:mm"
End Sub

Sub SetNumFormat()
    Selection.NumberFormat = "0.00"
End Sub

As mentioned in the comment, I found changing the cell format to "0.00" works well.  Times entered as "18.1" get converted to "18:10" (instead of 18:01) but actually that is ok by me.
The last 2 macros I assign to a couple of hot keys so that if I do make a mistake, I can quickly convert the cell's format back to numeric and end the value again.
Comment: The function you have above is overly complicated. Do you need all that error checking (like if it's in the range C6:F1000, etc.? As for the second part, you are using ConvertToTime but I think you should be using NumberFormat instead. Please see below for my take on an answer. :)
Comment: The range checking is useful as I am only entering time values in those cells - I do not want actual numeric values to be converted into times
Comment: Happy to see you found a solution that works (and thanks for posting it) and that Craig got the accept. If you found my answer helpful, an upvote would be appreciated, though! ^^
Answer: If you change the format of the cell to text (Format Cells -> Text), this will keep the 18.10 and allow you to parse the value easier.
Edit: When you run your macro add a line similar to:
Selection.NumberFormat = "h:mm AM/PM"

This should then reformat the cells a "time" format.
Comment: But ideally I would actually want them formatted as times!  Still your suggestion does work.  Unless someone can think of a nicer solution I will mark it as the accepted answer - though IMO it is a work around and not the answer.
Comment: I would also suggest making the cells as text then type away. Then do search replace to change . To : and then change format to time.
Answer: If all you want to do is change 18.10 to 18:10 then click the upper left corner of the sheet to select all cells, and change format to text. Then type away and do a search & replace for "." and ":" when you are done.
If you want, here's a fun way to auto format what you enter as time as you type it. In the VBA editor double click Sheet1 or whatever sheet you are working on and then enter this code:
Private Sub Worksheet_Change(ByVal Target As Range)

If InStr(Target.Value, ".") <> 0 Then
    Application.EnableEvents = False
    Target.Value = Replace(Target.Value, ".", ":")
    Target.NumberFormat = "h:mm AM/PM"
    Application.EnableEvents = True
End If

End Sub

What this does is first check if there is a "." in the cell you just changed or typed in. If there is, it turns off events (so the change it's about to do doesn't trigger another change event), then it replaces the "." with ":". It then converts it to the time format.
Here's an example of what happens. One note: For xx:30 you need to type an extra "." so that Excel doesn't get confused.

1.15   will become   1:15 AM
13.15   will become   1:15 PM
16:30.  will become   4:30 PM


Intersection of $n-1$ dimensional subspaces...

Question: Let $V$ be an $n$-dimensional vector space over $\Bbb R$. Show that every one dimensional subspace is the intersection of all $n-1$ dimensional subspaces containing it.
I honestly have no clue on this one.
Comment: I suggest you think about the case of a three dimensional vector space. Can you *see* why every line is the intersection of two planes? If so, then can you *prove* this rigorously? Alex has provided an excellent answer below and it's also worth thinking about his answer geometrically (in the three-dimensional case). What do the two planes look like whose intersection is a line in the case $n=3$ of his answer?
Comment: I can definitely see why a line is the intersection of two planes. I cannot prove it rigorusly. I finished the proof of this today in the general case though. I understand the problem intuitively.
Answer: Hint: Pick a basis $\{x_1\}$ for the line. Extend this to a basis $\{x_1,\ldots,x_n\}$. Clearly the line is in the intersection of all $n-1$ dimensional subspaces containing it, and to show the converse what if you considered $H_2,\ldots,H_n$ where $H_i=\text{span}\{x_j:j\ne i\}$.
Comment: So then the intersection of all such $H_I$ is in the space generated by $x_1$. Correct?
Comment: Correct. (empty space)
Answer: Let the one-dimensional subspace be $V=\mathrm{span}(\mathbf{v})$.  If $\mathbf{w} \not\in V$, then $\mathbf{w}$ is a linear combination of $\mathbf{v}$ and a non-zero vector $\mathbf{u}$ orthogonal to $\mathbf{v}$ ($\mathbf{u}$ is the vector rejection, according to Wikipedia).  If $\mathbf{u}=(u_1,u_2,\ldots,u_n)$, then the $1 \times n$ matrix $$\left(
\begin{matrix}
u_1 & u_2 & \cdots & u_n \\
\end{matrix}
\right)$$ has an $(n-1)$-dimensional null space, by the Rank-Nullity Theorem.  Moreover:

$\mathbf{v}$ is in this null space, since $\mathbf{u}$ and $\mathbf{v}$ are orthogonal.
$\mathbf{u}$ is not in this null space, otherwise $\mathbf{u} \cdot \mathbf{u}=0$, implying $\mathbf{u}$ is the zero vector.
Hence $\mathbf{w}$ is not in this null space, otherwise $\mathbf{u}$ could be formed from a linear combination of $\mathbf{w}$ and $\mathbf{v}$.

Thus, for any $\mathbf{w} \not\in V$, we have found an $(n-1)$-dimensional subspace containing $V$ but not $\mathbf{w}$.
The converse is true by definition (if $\mathbf{w} \in V$, then its in all $(n-1)$-subspaces contain $V$, and hence their intersection also contains $V$).


How to find the value of x using the Pythagorean theorem of the following right angle?

Question:
How would i go on to find the value of x? or the height? I thought of using sin() but what angle would i take it? Also the directions said to use the pythagorean theorem? the base is in total 26? do i divide by 3? but the middle part isn't of the same size.
Comment: is the angel at P the same as the angle at L?
Answer: Hint:
We shall first find the horizontal length. Note that the left triangle and the right triangle are the same, just reflected over. Subtract $5$ from $26$ to get $21$ as the horizontal length of both triangles. Then divide by $2$ to get the horizontal length of one triangle. Then, use Pythagorean Theorem to determine $x$.


Drupal hook_theme() Template Issue

Question: I am creating a block and I cannot get it to render correctly. I need to render a list of links but it is not working and it is showing nothing on the page.
I have the hook_theme() function like this:
function list_city_theme() {
  return array(
    'list_city_display' => array(
      'variables' => array(
        'title' => NULL,
        'locations' => NULL
      ),
      'template' => 'filter-by-city--display.tpl.php',
    ),
  );
}

And heres where i'm trying to set the theme inside the block view function:
$args = array(
  'title' => 'Filter by Town / City',
  'locations' => $locations
);
$block['content'] = theme('list_city_display', $args);

Answer: It is working for me. I have created a module called testtheme and mytemplate.tpl.php file is under testtheme/templates/.
Please try following sample code

/**
 * Implements hook_block_info().
 */
function testtheme_block_info() {
  $blocks['testtheme'] = array(
    'info' => t('Test Theme'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function testtheme_block_view($delta=0) {
  $black = array();
  if ($delta == 'testtheme') {
    $block['subject'] = t('Test Theme');
    $args = array(
      'title' => 'Filter by Town / City',
      'locations' => 'Bangalore',
    );
    $block['content'] = theme('list_city_display', $args);
  }
  return $block;
}

/**
 * Implements hook_theme().
 */
function testtheme_theme() {
  $path = drupal_get_path('module', 'testtheme');
  return array(
    'list_city_display' => array(
      'variables' => array(
        'title' => NULL,
        'locations' => NULL
      ),
      'template' => 'mytemplate',
      'path' => $path . '/templates',
      'type' =>'theme',
    ),
  );
}

Answer: To View the contents in a block must be implemented hook_block_view
/**
 * Implements hook_block_view().
 *@param $delta
 */
function list_city_block_view($delta='') {
  $block = array();
  switch($delta) {
    case 'block_name' :
      $block['content'] = theme('list_city_display', array('result' => array('title'=> NULL,'locations' => NULL)));
      break;
  }
  return $block;
}

Drupal hook_theme() Template Issue


Chrome extension: chrome local storage is not set instantly

Question: I am having strange issues with Chrome Local storage setting and retrieval.
In background.js I am setting it when a certain URL's HTML is fetched once the page loading is completed and then in content.js I am fetching values from local storage. At times it is stored and fetched instantly while other times results.html is undefined. And if I use chrome.storage.local.clear() it makes it more worst, make you to refresh the page 2-3 times at least. Below is my code:
background.js
chrome.runtime.onMessage.addListener(
    async function(request, sender, sendResponse) {
        // Reset storage
        // chrome.storage.local.clear() // it is lagging refreshing values
        sendResponse("bar")
        // Check whether it is correct URL
        var url = 'http://localhost:8000/get.php?url='+request
        console.log('URL for AJAX =',url)
        var result = await sendReq(url)
        var json_result  = JSON.parse(result)
        var status = json_result['status']
        var rules = []
        console.log('Status = '+status)

        if(status == 'ok') {
            rules = json_result['msg']['rules']
            chrome.storage.local.set({'rules': rules}, function() {});

            url = 'http://localhost:8000/read.php?url='+request
            result = await sendReq(url)
            // console.log(result)
            chrome.storage.local.set({'html': result}, function() {}); // this goes undefined if the URL of visiting page is changed.
        } else {
            // To check on content script
            chrome.storage.local.set({'html': '__FAIL__'}, function() {});
        }
    }
);

content.js (Using JQuery)
  $(function() {
    // console.clear()
    console.log('The Agile Super Cluster extension cleared all previous output')
    chrome.storage.local.get(['html','rules'], function(result) {
        // Do not perform things below if it is not a relevant Super Cluster URL
        if(result.html == '__FAIL__' || typeof (result.html) == 'undefined') {
          return
        }
      .....

// Out of onReady() block
chrome.runtime.sendMessage(
        url,
        function (response) {
            console.log('Sending Response')
            console.log(response);
        }
    );

Comment: Waiting on async tasks is technically optional, yes. However, if you wish to use the results of that task, you need to wait for it to have results.
Comment: [`.set()`](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/set) is asynchronous and returns a promise. You'll need to wait for it to resolve via `await`, `.then()`, etc.
Comment: @Ouroborus I am storing locally, plus, official documentation example says it is optional
Answer: The solution is to use messaging correctly so you can wait on the result reliably.

remove chrome.storage, it's not necessary for this task;
remove async from onMessage listener (why?) and use a separate async function to get info;
return the result via sendResponse + return true.

content.js:
chrome.runtime.sendMessage(url, res => {
  console.log(res);
  if (res.html) {
    // use `res.html` here
  }
});

background.js:
const API_GET = 'http://localhost:8000/get.php?url=';
const API_READ = 'http://localhost:8000/read.php?url=';

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  getInfo(request).then(sendResponse);
  return true; // keep the channel open for asynchronous sendResponse
});

async function getInfo(url) {
  const res = JSON.parse(await sendReq(`${API_GET}${url}`));
  return res.status === 'ok' ? {
    rules: res.msg.rules,
    html: await sendReq(`${API_READ}${url}`),
  } : {};
}

Comment: You made it very clear and compressed. Actually I wanted to use messaging and if you remember I asked you question here (https://stackoverflow.com/questions/72846615/chrome-extension-uncaught-in-promise-error-could-not-establish-connection-r?noredirect=1#comment128669091_72846615) as I was having issue to use it from background.js file. I will now build things up based on your suggestions.


C++ check if statement can be evaluated constexpr

Question: Is there a method to decide whether something can be constexpr evaluated, and use the result as a constexpr boolean? My simplified use case is as follows:
template <typename base>
class derived
{
    template<size_t size>
    void do_stuff() { (...) }

    void do_stuff(size_t size) { (...) }
public:
    void execute()
    {
        if constexpr(is_constexpr(base::get_data())
        {
            do_stuff<base::get_data()>();
        }
        else
        {
            do_stuff(base::get_data());
        }
    }
}

My target is C++2a.
I found the following reddit thread, but I'm not a big fan of the macros. https://www.reddit.com/r/cpp/comments/7c208c/is_constexpr_a_macro_that_check_if_an_expression/
Comment: Maybe you can do something with [`std::is_constant_evaluated`](https://en.cppreference.com/w/cpp/types/is_constant_evaluated)?
Comment: @AartStuurman: What is `do_stuff` that it can run at compile time or runtime, but itself should not be `constexpr`? Wouldn't it make more sense to just make it a `constexpr` function, and pass it the value of `get_data` as a parameter?
Comment: Hmm, the body of a `if constexpr` will only be evaluated if the expression in the `if constexpr` is true at compile time. Is that what you are looking for?
Comment: But what if the test in the if constexpr([test]) is not evaluatable at compile time?
Comment: https://en.cppreference.com/w/cpp/language/if
Comment: If it's not evaluateable at compile time then what would you have the compiler do except error out or evaluate at run time?
Comment: If it can be evaluated at compile time, the first body should be executed. Else the second runtime body should be executed. I'm currently investigating 0x5453 's recommendation.
Comment: Meanwhile I've revised my design choice indeed, but I think this an interesting question nonetheless :)
Answer: Here's another solution, which is more generic (applicable to any expression, without defining a separate template each time).
This solution leverages that (1) lambda expressions can be constexpr as of C++17 (2) the type of a captureless lambda is default constructible as of C++20.
The idea is, the overload that returns true is selected when and only when Lambda{}() can appear within a template argument, which effectively requires the lambda invocation to be a constant expression.
template<class Lambda, int=(Lambda{}(), 0)>
constexpr bool is_constexpr(Lambda) { return true; }
constexpr bool is_constexpr(...) { return false; }

template <typename base>
class derived
{
    // ...

    void execute()
    {
        if constexpr(is_constexpr([]{ base::get_data(); }))
            do_stuff<base::get_data()>();
        else
            do_stuff(base::get_data());
    }
}

Comment: Comma operator SFINAE... my mind goes BOOM.
Comment: Intriguing solution... this way you get the same result of my custom type traits but more synthetically and, above all, the exact expression verified (`base::get_data()`) is embedded in the argument and not hard-coded as in my solution. Very nice. I have to remember it.
Comment: I am accepting this, because it is an answer to the a generic case of the question. max66 answer is also very useful(in non-c++2a cases), but requires repetition for every usage :)
Comment: An enlightening solution to the problem. I have been doing some testing on this, and I believe that the use of the comma SFINAE is unneeded and I am pretty  sure that a template of the form `template`, where my `T` is your `Lambda` would equally suffice.
Comment: On second thoughts, the comma SFINE is needed due to void return type of lambda. (in my testing I was using a lambda akin to `[]{  base::get_data(); return true;}`, which is always non-void.
Answer: Not exactly what you asked (I've developer a custom type trait specific for a get_value() static method... maybe it's possible to generalize it but, at the moment, I don't know how) but I suppose you can use SFINAE and make something as follows
#include <iostream>
#include <type_traits>

template <typename T>
constexpr auto icee_helper (int)
   -> decltype( std::integral_constant<decltype(T::get_data()), T::get_data()>{},
                std::true_type{} );

template <typename>
constexpr auto icee_helper (long)
   -> std::false_type;

template <typename T>
using isConstExprEval = decltype(icee_helper<T>(0));

template <typename base>
struct derived
 {
   template <std::size_t I>
   void do_stuff()
    { std::cout << "constexpr case (" << I << ')' << std::endl; }

   void do_stuff (std::size_t i)
    { std::cout << "not constexpr case (" << i << ')' << std::endl; }

   void execute ()
    {
      if constexpr ( isConstExprEval<base>::value )
         do_stuff<base::get_data()>();
      else
         do_stuff(base::get_data());
    }
 };

struct foo
 { static constexpr std::size_t get_data () { return 1u; } };

struct bar
 { static std::size_t get_data () { return 2u; } };

int main ()
 {
   derived<foo>{}.execute(); // print "constexpr case (1)"
   derived<bar>{}.execute(); // print "not constexpr case (2)"
 }

Comment: This is madness, this use of the comma operator, the long/int overload... Have an upvote. :/
Comment: @GregoryNisbet - Yes. Because, for the language so for the compiler, they remain different types.
Comment: @matovitch - never underestimate the power of the comma operator }:‑)
Comment: Will this work on platforms where `sizeof(long)` is equal to `sizeof(int)`?
Answer: template<auto> struct require_constant;
template<class T>
concept has_constexpr_data = requires { typename require_constant<T::get_data()>; };

This is basically what's used by std::ranges::split_view.


Convert 2 bytes into an integer

Question: I receive a port number as 2 bytes (least significant byte first) and I want to convert it into an integer so that I can work with it. I've made this:
char buf[2]; //Where the received bytes are

char port[2];

port[0]=buf[1];

port[1]=buf[0];

int number=0;

number = (*((int *)port));

However, there's something wrong because I don't get the correct port number. Any ideas?
Comment: also 2 bytes vs 4 bytes: short vs int
Comment: use uint16_t to do the cast
Comment: is your endianness the same?
Answer:
I receive a port number as 2 bytes (least significant byte first)

You can then do this:
  int number = buf[0] | buf[1] << 8;

Comment: @user1367988 Just beware in case `char` is signed on that platform.
Comment: @AnttiHaapala--СлаваУкраїні How is this incorrect? It looks equivalent to Joachim's.
Comment: **This answer is wrong and will break badly on x86 if either of the bytes has sign bit set, unless you use unsigned char for the buffer.**

@kwc joachim's says: "if you make it unsigned char". I remove the comment because whereas Joachim's answer is more correct it is still not 100 % portable - for 16 bit ints it invkes undefined behaviour. But this answer is very much broken on x86 and signed chars, unless the type of the buffer is changed. Since both are converted to signed, if either byte is
Answer: If you make buf into an unsigned char buf[2];, you can simplify it to:
number = (buf[1] << 8) + buf[0];

Answer: I appreciate this has already been answered reasonably. However, another technique is to define a macro in your code eg:
// bytes_to_int_example.cpp
// Output: port = 514

// I am assuming that the bytes the bytes need to be treated as 0-255 and combined MSB -> LSB

// This creates a macro in your code that does the conversion and can be tweaked as necessary
#define bytes_to_u16(MSB,LSB) (((unsigned int) ((unsigned char) MSB)) & 255)<<8 | (((unsigned char) LSB)&255)
// Note: #define statements do not typically have semi-colons
#include <stdio.h>

int main()
{
  char buf[2];
  // Fill buf with example numbers
  buf[0]=2; // (Least significant byte)
  buf[1]=2; // (Most significant byte)
  // If endian is other way around swap bytes!

  unsigned int port=bytes_to_u16(buf[1],buf[0]);

  printf("port = %u \n",port);

  return 0;
}

Answer: Least significant byte:
int number = (uint8_t)buf[0] | (uint8_t)buf[1] << 8;
Most significant byte:
int number = (uint8_t)buf[1] << 8 | (uint8_t)buf[0];
Answer: char buf[2]; //Where the received bytes are
int number;
number = *((int*)&buf[0]);

&buf[0] takes address of first byte in buf.
(int*) converts it to integer pointer.
Leftmost * reads integer from that memory address.
If you need to swap endianness:
char buf[2]; //Where the received bytes are
int number;
*((char*)&number) = buf[1];
*((char*)&number+1) = buf[0];

Comment: this answer is incorrect. It violates strict aliasing and also possibly alignment requirements.

Convert 2 bytes into an integer


Route matching with GetVirtualPath

Question: I've got the following routing in my application...
public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute(
    "Branding",
    "foo/bar.css",
    new { controller = "DynamicContent", action = "CSS" }
  );

  routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Account", action = "Index", id = UrlParameter.Optional }
  );
}

I'm using Martijn Boland's paging mechanism and it eventually makes the following call:
var virtualPathData =
  RouteTable.Routes.GetVirtualPath(this.viewContext.RequestContext, pageLinkValueDictionary);

I've verified that my controller and action in RequestContext are valid.  But once this call is made, virtualPathData references the URL for foo/bar.css.  I have verified that URLs map to the correct controller/action.  If I comment out the route above leaving the default, virtualPathData's URL corresponds to the right controller/action.
I've also tried the following line and I have the same result.
//var virtualPathData =
  RouteTable.Routes.GetVirtualPathForArea(this.viewContext.RequestContext, pageLinkValueDictionary);

Can anyone help me figure out what I'm doing wrong?
Answer: Unfortunately, I think the logic for generating URLs doesn't handle static URLs very well. I believe one thing you can do is:
routes.MapRoute(
    "Branding",
    "{controller}/bar.css",
    new { controller = "DynamicContent", action = "CSS" },
    new {controller="foo"}
  );

Try that out.
Comment: Thanks Phil, it works and is much cleaner than my proposal (which in retrospect is much like a double-negative) - I appreciate it!
Answer: I'm still not exactly sure why I was seeing the behavior above, so if anyone wants to chime in with their ideas feel free.
That said, if someone else hits the same problem, I was able to overcome it by reversing the route order with the more ambiguous default route being added first with a NotEqual constraint to ensure that the DynamicContent route was hit as needed.
routes.MapRoute(
  "Default",
  "{controller}/{action}/{id}",
  new { controller = "Account", action = "Index", id = UrlParameter.Optional },
  new { controller = new NotEqual("DynamicContent") }
);

routes.MapRoute(
  "Branding",
  "foo/bar.css",
  new { controller = "DynamicContent", action = "CSS" }
);

For those who are wondering what NotEqual is, I found it on a blog.
public class NotEqual : IRouteConstraint
{
  private string _match = string.Empty;

  public NotEqual(string match)
  {
    _match = match;
  }

  public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
  {
    return String.Compare(values[parameterName].ToString(), _match, true) != 0;
  }
}

I'm certainly up for hearing about better ways of doing this OR why my original code wasn't completely working.

Route matching with GetVirtualPath


Filepond Image Uploader - setOptions on multiple instances

Question: Using the Filepond plugin, I want to have separate setOptions for each instance of Filepond. The problem is that I don't know how to get setOptions to work for each instance and not universally.
How do I set up the plugin to recognize each .filepond input as it's own instance, but allow for different setOptions on each?

/*
We want to preview images, so we need to register the Image Preview plugin
*/
FilePond.registerPlugin(
  // encodes the file as base64 data
  FilePondPluginFileEncode,

  // validates the size of the file
  FilePondPluginFileValidateSize,

  // corrects mobile image orientation
  FilePondPluginImageExifOrientation,

  // previews dropped images
  FilePondPluginImagePreview
);
// get a collection of elements with class filepond
const inputElements = document.querySelectorAll(".filepond");

// loop over input elements
Array.from(inputElements).forEach((inputElement) => {
  // create a FilePond instance at the input element location
  FilePond.create(inputElement);
});

FilePond.setOptions({
  labelIdle: 'Drag & Drop your file or  Browse '
});
.filepond--item {
  height: 90px !important;
  width: 90px;
  overflow: hidden;
}

/**
 * FilePond Custom Styles
 */

.filepond--drop-label {
  color: #4c4e53;
}

.filepond--label-action {
  text-decoration-color: #babdc0;
}

.filepond--panel-root {
  border-radius: 2em;
  background-color: #edf0f4;
  height: 1em;
}

.filepond--item-panel {
  background-color: #595e68;
}

.filepond--drip-blob {
  background-color: #7f8a9a;
}
<link href="https://unpkg.com/filepond/dist/filepond.min.css" rel="stylesheet" />
<link href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css" rel="stylesheet" />

<input type="file" class="filepond filepond--first" name="filepond" multiple data-max-file-size="3MB" data-max-files="5" />

<input type="file" class="filepond filepond--second" name="filepond" multiple data-max-file-size="3MB" data-max-files="1" />

Answer: FilePond.setOptions will assign options to all instances.
Calling FilePond.create will return the created instance and this instance will have a setOptions method as well. So you can call myInstance.setOptions if you want to set options for a specific instance.


Does there exist an almost everywhere smooth function that does not have a local extrema at an endpoint of its domain?

Question: Does there exist a function $f:[0,\infty)\to {\mathbb{R}}$ that is smooth almost everywhere such that $(0,f(0))$ is not a local extrema?
Comment: Huh? Does $f(x) = x \sin(1/x)$ count?
Comment: @CameronWilliams: Your function has a local max at $0$. Note OP's domain.
Comment: @TedShifrin I'm silly. I meant to write $f(x) = (x+1)^2$. Here I'm assuming by local extrema he means $f\,'(x) = 0$ (as per usual) but who knows.
Comment: is $f$ assumed to be continuous?
Comment: Could you give a definition of "almost smooth".  I couldn't find one anywhere.  Do you mean differentiable except for some points?
Comment: Since @Evan's comment furnishes the desired example, I suggest that it be written up as an answer.
Comment: I was hoping that $f'(0)=0$, but $(0,f(0))$ is neither a local minimum or a local maximum.
Answer: (Comment to answer)
Let $g(x) = x \sin(1/x)$ for $x \neq 0$ and $g(0)=0$. It is a smooth function except at $0$ (though continuous). However $(0,g(0))$ is not a local extrema (there are points as close to $0$ as you wish that take values above and below $0$).
Answer: Note that we can easily turn this into a smooth example. Let $h$ be a smooth function with all derivatives at $0$ equal to $0$. For example, take $h(x)=e^{-1/x^2}$, $x\ne 0$, $h(0)=0$. Set $f(x)=h(x)\sin(1/x)$, $x\ne 0$, $f(0)=0$.
Comment: does your function $f$ have a derivative at 0?
Comment: Yes. Infinitely many derivatives! They're all $0$.
Comment: I don't understand. Since $h'(0)=0$, the product rule gives $f'(0)=h(0)(\sin(1/x))'|_{x=0}$. But why is $(\sin(1/x))'|_{x=0}$ defined?
Comment: You can't use the product rule in this setting. You have to go back to the *definition* of the derivative and use the squeeze principle, noting that $|\sin(1/x)|\le 1$.


Push Notification not working in foreground IOS

Question: push notification is working perfectly fine when app is in background, the main issue arises when the app is in foreground. I am able to receive the payload but the notification is not shown in the notification banner
payload received below

{"data": {"fcm_options": {"image": "https://importduniya.com/dealer/particular/TrustyCane.jpg"}}, "messageId": "1591459535622805", "mutableContent": true, "notification": {"body": "Test123", "ios": {}, "title": "Test"}, "sentTime": "1591459535"}

I think the below function is not getting called when the app is in foreground

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  NSLog(@"will-present");
  completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}
Answer: You should implement application:didReceiveRemoteNotification:fetchCompletionHandler: as well


Is laravel-ide-helper compatible with laravel 5.3?

Question: laravel-ide-helper github: https://github.com/barryvdh/laravel-ide-helper
When I use "composer install" throw these errors
[Symfony\Component\Console\Exception\CommandNotFoundException]
There are no commands defined in the "ide-helper" namespace.
Script php artisan ide-helper:generate handling the post-install-cmd event returned with an error
[RuntimeException]
Error Output:
Is laravel-ide-helper compatible with laravel 5.3?
Answer: adding the line
'Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider',
 in app.php 'providers' array fixed it.
Comment: ERROR  There are no commands defined in the "ide-helper" namespace.
Script @php artisan ide-helper:generate handling the post-update-cmd event returned with error code 1.

And solve with your suggest. Thanks


Are there any tools that can monitor SNMP, JMX & TIBCO Hawk in one place?

Question: Our Operations department is getting twitchy about too many monitoring tools so are there any tools that can handle SNMP, JMX and TIBCO Hawk all in one application?
Comment: SO is for programming related questions
Answer: If I understand your question correctly, your system administrators want a single console that can handle, Hawk, JMX and SNMP.
Hawk Console can do this because Hawk agents can bridge JMX and SNMP (if you use the additional Hawk SNMP adapter).
Alternatively, if you prefer a different console then there are two common ways to get Hawk alerts to that console:

Use the Hawk SNMP Adapter to convert Hawk alerts into SNMP traps. The adapter is seperately licensed.
Run Hawk Alert Server (bundled with Hawk) which persists Hawk alerts to a logfile, then get your console to trawl the logfile.
Answer: Try to look at the Mirador software from those Swiss guys:
http://www.centeractive.com/index.php?option=com_content&view=article&id=12&Itemid=7&lang=en
Extensive hawk support
Answer: SNMP & JMX are monitored by a product Manage Engine Applications Manager. You can give it a try.Regarding Tibco Hawk am also in search of a tool.Do let me know if you find one,.
Answer: What about SL Corporation's RTView product ?
It handles SNMP, JMX, and all the TIBCO products


BootStrap DropMenu Not Working

Question: I have created a dropdown menu but it is not working:

                Menu

Tom

Greg

Jane

I am using Bootstrap CSS framework and have included all the appropriate CSS and JS files. What am I doing wrong? While looking at other questions similar to mines, I haven't been able to figure it out.
Comment: You have HTML errors...try validating that first.
Comment: >_< Sorry for the typos. I fixed them
Answer: One solution may be that you are not referencing the jquery.js source before bootstrap.js source
Answer: You're missing some key elements.
This is what your dropdown element should look like.

This goes with the dropdown-toggle class.
data-toggle="dropdown" aria-expanded="false"

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

 Menu

Tom

Greg

Jane

Answer: First mistake was a couple of quotation marks missing. On top of that, you are not following the syntax and classes listed here: http://getbootstrap.com/components/#dropdowns
Here is the correct version:

  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Menu

  </button>

Tom

Greg

Jane

BootStrap DropMenu Not Working


routing behaviour (PAT/NAT)

Question: <code>                                    |(eth0: 220.127.116.11)
                       +--------------+
                       |              |
                       |  NAT router  |
                       |              |
                       +--------------+
                         |(eth1: 192.168.0.1)
                         |
                 ----------------
                (                )
    +--+       (                  )
    |__|------(   192.168.0.0/24   )
   /____\      (                  )
   Host-A       (________________)
(192.168.0.2)
</code>

Assuming we have above network situation and a destination PAT/NAT rule configured on the NAT router for eth0 which forwards all incoming packages with destination port TCP/80 to Host-A (192.168.0.2) I have following question:
What happens when a Host-B (192.168.0.10) in the local networks sends a HTTP request to 184.108.40.206? Some routers seem to manage this situation correctly others not. Is there a technical expression describing this situation? How can I find out which router can manage such internal request on an external ip and which not?
Comment: I think using of DNS split horizon would be the easiest way
Answer: The technical term for this would be NAT hairpinning or NAT U-turns. Not all home routers do this correctly, but those are off-topic here. Any router used in a professional environment would let you set this up properly.
Another way to "solve" this problem is split DNS views, where internally hostnames would resolve to the internal IP addresses instead of the external ones. In a more complex network I would be in favor of that, but for what you sketch above, NAT hairpinning is easier.
Comment: Because Cisco...
Comment: Yeah, why would we stick to one term if we can have four :)
Comment: NAT hairpinning is also known as NAT reflection or NAT loopback

routing behaviour (PAT/NAT)


With black keys, does one use curved or straight fingers; what about curved or straight between the black keys?

Question: When I play piano chords with sharps or flats, should my longer finger on the black key be straight or curved? I have tried both approaches, but I can't see any difference.
Also, should my fingers on those chords inside the black keys be straight or curved?
Answer: This depends on many factors: which hand, hand size, hand span, finger length, the specific number and arrangement of notes in the chord, fingering, articulation, and what else is happening in the music all can influence whether and how flat or curved each finger might be.
However, given an individual chord, there is a general approach that can be taken in determining the appropriate amount of flatness or curved-ness for each finger.

Place your hand, as relaxed as possible, so that the fingers to play the outer (highest and lowest) notes of the chord are resting gently on those notes.
Of the remaining fingers, look to see which finger is closest to which remaining chord tone, if any, and gently adjust that finger's position, including any flattening or curling, to that note.

This process will generally given the most comfortable hand/finger position for a chord.
For chords in which the highest and/or lowest note is a black key, remember to move your entire hand toward the fall board in order to bring your fingers closer to the keys. Twisting or stretching to reach them is back for your hand and arm health as well as maintaining ease of execution. Of course, the closer your hand is to the fall board, the more one might need to curve the longer fingers.
Answer: TLDR: As long as you touch all the keys on the right part of your finger tips (having the natural angle of around 30-60 degrees: not close to 90 degrees that your nail touch the keys or close to 0 degree that it's no longer your finger tips that touch the keys), your wrists are in the straight & natural position, your press the keys optimally (not too inside, and not at the tip of the key), you direct the energy from the arm (rather than from your wrist / fingers), and your hand maintains a stable curve during the key press (i.e. fingers remain stiff during key down and key up), it doesn't matter how straight/curvy your middle finger is because it depends on how spread-out the chords are and the combination of black / white keys in the chord.  The longer section below has more details.

This YouTube playlist from "Piano From Scratch" is one of many good video introductions on how to have a good hand placement.  I suggest first reviewing the first video showing how you can naturally move your hand across the keyboard controlled by your arm while the finger tips stay softly in contact with the white keys, and your wrist and natural finger curves stay in formation.  Follow the 2nd warm up exercise for the natural lifting of the hand and the spreading of fingers to form chords.  Don't be tense, gripping, or digging in.  The third section shows how to remold the finger curves for different inversions of chords or for another chord.  Around minute 8:00 he shows how to move the hand further in when the thumb needs to hit a black key.
In the second video he goes through more good hand placement techniques.  One of them addresses your concern: playing a chord where your middle finger needs to play the black key while the rest on white keys such as the D major chord (root position).  He covers this starting minute 4:12 (Basic Chord Positions & Tips):

First, note that the curve stays natural, and make sure to place the fingers forward enough so that the thumb doesn't dangle.
Second, when there is a mixture of black and white keys (starting minute 5:05), you need to move the hand slightly more forward, so you can press all keys comfortably while maintaining the curve (for example, you shouldn't play the black keys on the tip).  Picture of him playing the D major chord in minute 5:19.
Third all fingers need to come down together, so make sure the hand is in position before you press the keys.

Good luck!
Comment: @Aaron I (hopefully) improved the description to avoid misunderstanding.  I agree that the curve is the least important compared to other factors I mentioned.
Answer: I don't think it's a particularly important issue to dwell on. It will depend on the relative length of each finger (and thumb) on your hand, and that's a factor that won't be the same for everyone, by any means. There's also the amount of articulation available for those fingers. So how can there be any hard and fast rule?
It will also vary with how one is playing - gently or firmly. That will necessitate a difference in curvature/straightness - or at least it does in my playing! Watching world class players, some will play with lower wrists, straighter fingers, others the opposite. True, with fast runs, curved fingers are the menu for the day, but that's not what you ask.
The best way is what suits you best! At least you've addressed the 'problem', and come up with some alternatives. An excellent thing to do, when playing any instrument. As time goes on, your fingers will naturally find their best position - and that will vary with what's being played, and how it's played. It's similar to 'which fingering should I use?', and the answer there is the same. Whatever suits you and the piece in question best. I don't believe there's a one-fits-all answer.
Dvers - please explain why!!