Drupal module development - How to build admin items list?

Question: I'm creating a Drupal module and I would like to know how to build the admin panel table with the list of each items that I've been created with the module.
What is the hook to use ? and/or the API function... ? I did not found it.
All the tutorials that I read on the web explain how to create a form for submitting content but no one explain how to create the list of the content that have been submitted with the form.
You can see in the joined picture two examples of that I want to do.
Answer: I think you have at least two possibilities to proceed.
First, you can use "Views" module to display a list of whatever you want (you can easily configure it to display all contents of a certain content-type that the user currently seeing the page created, etc, etc). You can inspire yourselft with this article about creating an administration page with Views 2 (http://zugec.com/2010/08/create-administration-pages-views-2). It is not very different.
If you want to do it programmatically,  you can always create a "page" that displays whatever you want using hook_menu(). Just set the path under "admin/" and permissions the way you want. Use the page callback function to make the appropriate query (select the nodes you want, created by the current user, order them, sort them, etc...) and to display the results.
If you want more explanations about one of the two solutions provided up there, just ask and I'll develop deeper :-)
Comment: Hello Djouuuuh, Thank you for the answer. I don't wanna use Views module, I just wanna build my own module admin page. I already use "hook_menu()" for the form of the module. I hoped that there's a function that build the table of entries, a function that can do this without having to rewrite all the code, such as "drupal_admin_form" function to build a form, but maybe I'm wrong...
Comment: No I think there is no such thing and that you have to make that list and form manually. If you don't want to use Views, well good luck with your code :-) else, you can try with Views and Views Bulk Operations modules.
Comment: I found the solution for build my table, I use "theme_table()" function. Now I've a problem with my edit link. For each item I make a link to an edit form. I would like to know how can i pass variables to my "items/edit" page, I try "items/edit/?var=value", but It doesn't work... How can I do this ??
Comment: Here is how you can pass parameters with the l() function: l('Edit link', 'node/123/edit', array('query' => array('param' => 'value')));
Comment: That's working good ! Thank you... I've another little problem, I would like to add a class to a link, so I do this : `l('Informations & Documentation', 'admin/config/tamtamimporter/infos-doc', array('class' => array('module-link-help'))) `, but It doesn't work
Comment: That's because you forgot the attributes array that contains the classes array: `l('Informations & Documentation', 'admin/config/tamtamimporter/infos-doc', array('attributes' => array('class' => array('module-link-help'))))`
Comment: It's working good, thank you very much for your help !!
Comment: You're welcome @MOWebCreation. If my answer suited you, could you please check it as "right answer"? :-)


ASP.Net MVC 2 - How to stop the view from using prefixes on fields?

Question: ASP.Net Html.TextBoxFor (and the other XxxxxFor editor helper methods) default to rendering a field prefix. How do I disable field prefixes so it simply renders the property name as the Name/ID?
Here's an example:
<%= Html.EditorFor(m => chart.Title) %>

is rendered as:
<input id="Chart_Title" name="Chart.Title" type="text" value="">

I would prefer it to be rendered as:
<input id="Title" name="Title" type="text" value="">

Answer: There's a parameter in an overload of EditorFor called htmlFieldName. Specify your name here.
Answer: The helpers take whatever you give it.  So you need to pass in just the "Title" portion of the variable; maybe try assigning title to a variable, and use Html.EditorFor for that Title variable, and that might give you a different response.
The reason it does that is the helpers are setup to reflect from the Model context, so typically you may see Model.Chart.Title, and as such, the helpers create this path in the name so it can post the entire model back to the action method, if it needed to.
HTH.


Calculate effect of independent variable

Question: If $a\times b\times c=t$ and I change $a$, $b$, and $c$, how do I calculate the effect of each change.
I believe the equation is: $(a+\Delta a)(b+\Delta b)(c+\Delta c)=(t+\Delta t)$, and then I solve for $\Delta a$, $\Delta b$, and $\Delta c$.
Is this correct? And how do I describe what I'm solving for?
Comment: Search our site for [delta method](http://stats.stackexchange.com/search?tab=relevance&q=delta%20method).
Comment: As phrased this doesn't appear to be a statistical question. If it is, could you clarify where/how?
Answer: Well, you could use partial differentiation for computing effect of small changes -
$\partial t=ab\,\partial c+ac\,\partial b+bc\,\partial a$
Informally, you could interpret that as a solution to $\Delta t$ in the limit when the changes are small, and think of $\partial t=\lim_{\Delta a,\Delta b,\Delta c \to 0}\Delta t$.

So, for example if a=5, b=3, c=4, and they change by .01, .02, .03, we have
$\Delta t \approx 5\times 3\times0.03+5\times4\times0.02+3\times4\times0.01=0.97$
And indeed, it is close to the real $\Delta t=(5.01\times3.02\times4.03)-(5\times4\times3)=0.97471$.
Comment: The full split can be computed thus. $\Delta t = (a+\Delta a)(b+\Delta b)(c+\Delta c)-abc = ab\Delta c+bc \Delta a+ac\Delta b\color{blue}{+a\Delta b \Delta c+b \Delta a\Delta c+c\Delta a\Delta b+\Delta a\Delta b\Delta c}$
Comment: My understanding is that there is a "short" solution, as you've described, which is close, but approximate. And there is the "long" version, which, using your example, would be: Δt=(5×3×0.03)+(5×4×0.02)+(3×4×0.01)+(5×0.02×0.03)+(3×0.01×0.03)+(4×0.01×0.02)+(0.03×0.02×0.01)=.9747060. What I'm looking for is the portion of .97 caused by the change in "a" which is .45, the change in "b" (.4) and the change in "c" (.12). How do I distribute the remaining .0047060?
Answer: Apply the log transform: $\ln t = \ln a + \ln b +\ln c$. The effect of each variable in your original setup depends on the values of other variables, much like an interaction term in regression. However, in the regression interaction terms are rarely included without the main effect. If your model is truly multiplicative, then I think that the log transform will help you understand the effects better.
Also, if you differentiate the log transformed equation, you get: $\Delta t/t=\Delta a/a+\Delta b/b+\Delta c/c$, which is also easy to interpret, it's a sum of relative effects.


breadcrumbs not displaying correctly for views

Question: I'm pretty new to the world of drupal so I'm hoping this will be a quick fix.
Anyhow here's the situation:
my breadcrumbs work correctly when hitting a node for example when i go to "contact" it prints out home > contact.  Now I have a view and when I go there things look ok. I go to events and it prints out home > events > view all. When I go to a subview like "tech events" however it spits out home > events > events > view all.
The code below is what is currently in place so I was wondering how to alter it to handle views or if anyone could point me to a good solution.
thank you
my code:
function custom_breadcrumb($variables) {
  $currentTitle = "";
  $trail = menu_get_active_trail();
  $currentNode = array_pop($trail);
  if( $currentNode ){
    $currentTitle = $currentNode['title'];
  }

  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {

    $output = '

';
    $output .= implode('

', $breadcrumb);

    if( $currentTitle ){
      $output .= '

';
      $output .= $currentTitle;
    }
    $output .= '

';

    return $output;
  }
}

any help would be awesome guys. thank you.
Answer: Okay so it still needs some work to be a little more generic but this basically handles the case. It checks to make sure that the content-type is not a node we check to see if there's an additional argument and append that to the breadcrumbs. if it is a node we just print out hte breadcrumb trail checking to make sure that we don't repeat things. If you use a page jump, fragments, or redirects you might get a repeat, i.e. home > stories > stories.  So here it is.
function custom_breadcrumb($variables) {
  $currentTitle = "";
  $trail = menu_get_active_trail();
  $currentNode = array_pop($trail);
  if( $currentNode ){
    $currentTitle = $currentNode['title'];
  }

  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
    $lastCrumb = NULL;

    $output = '
' . t('You are here') . '
';

    $output .= '

';

  for ($i = 0; $i < count($breadcrumb); $i++) {
    $curCrumb = strip_tags($breadcrumb[$i]);
    if ($i == 0) {
      $output .= $breadcrumb[$i];
      $lastCrumb = strip_tags($breadcrumb[$i]);
    } elseif (strpos($breadcrumb[$i], $lastCrumb) === false) {
      $output .= '

' . $breadcrumb[$i];
      $lastCrumb = strip_tags($breadcrumb[$i]);
    }
  }

  if (arg(0) != 'node' ) {
    $output .= '

';
    $output .= arg(1);
  } elseif( $currentTitle ){
    $output .= '

';
    $output .= $currentTitle;
  }
  $output .= '

';

  return $output;
  }
}

Answer: To be honest, I'd probably skip all the custom stuff and just use Path Breadcrumbs

This module is a solution for all problems with the breadcrumbs on
  your site!
Path Breadcrumbs module helps you to create breadcrumbs for any page
  with any selection rules and load any entity from the URL!

They're also exportable, so if you want them in code you can either export them and implement the default hook, or use Features.


Validation of zero-inflated negative binomial models

Question: For my overdispersed and zero-inflated data I have used a zero inflated negative binomial and a hurdle model, for comparison purposes.
I need to validate the model, i.e. see whether certain assumptions are fulfilled to check if the model is adequate for inference. However, I'm not able to find any information on the steps of validation of these models.
Side question: Is there a more elaborate way to compare hurdle and zero-inflated models, other than the AIC?
Does anyone have any suggestions?
Answer: For validating the ZINB or hurdle model, your first step could be to create a null model and compare the ZINB/ hurdle model and the null model using a likleihood ratio test. This will tell you whether your ZINB or hurdle model fits the data better than the null model, providing some validation of its utility. If so, you could proceed with methods such as cross validation and determining pseudo R2, though I don't have personal experience applying these methods to hurdle models.
Comment: That's a great suggestion! In "normal" regression models usually there is the F-test for that, what you suggested is a good alternative. Didn't occur to me. And what about visual analysis for validation?
Comment: @Bileobio Glad the suggestion was helpful. I haven't previously used visual analysis for validation of these model types, so I'm not positive. My go-to for most regressions is to look at marginal effect plots of individual predictors. If they look 'nice' and have reasonable confidence intervals, I feel good about the model


Why is orthogonality a requirement after $R^2$ for linear independence

Question: Geometrically it makes sense, as in $R^3$ coplanarity cannot be avoided unless you add a new direction but why is $R^2$ an exception?
Comment: It's not: The vectors $(0, 1)$ and $(1, 1)$ are independent and not orthogonal.
Comment: @user2654176 Orthogonality is not a requirement for linear independence, period.
Comment: Can't quite interpret what you mean by "after" here. Do you mean "for"? Orthogonality *isn't* a requirement for linear independence.
Comment: Maybe you are getting it backwards. It *is* true that if you have a set of pairwise orthogonal nonzero vectors, then they are linearly independent.
Comment: @user2654176: no, it is not.
Comment: I thought for $n \geq 3, R^n$ pairwise orthongality is the necessary condition for a list of linear independent vectors, and my question is why is $R^1$ and $R^2$ the exception
Comment: @Michael which part, the whole part?
Answer: It is not a requirement
Two vectors must be at right angles for them to be orthogonal. Sometime we require that the vectors themselves have unit length, but not always. In vector language, orthogonal is often used in the same way as perpendicular is with lines, i.e. at right angles.
The vectors $(1,0)$ and $(1,1)$ are linearly indepndent in the plane but they are not orthogonal. The angle between $(1,0)$ and $(1,1)$ is $45^{\circ}$. For orthogonality, we need the angle to be $90^{\circ}$.
Orthogonal vectors in the plane are always linearly independent, but the converse is false: there exist non-orthogonal vectors which are linearly independent.


Como atualizar um DataGridView ao alterar o outro?

Question: Tenho um DataGridView chamado gridProfissional que lista todos os profissionais que tenho cadastrado em uma tabela.
Tenho outro DataGridView chamado gridAgenda que lista os dias que o profissional atende.
Tenho uma função que funciona corretamente:
private void preencheGridAgenda()
{
    List<datum> listaData = new List<datum>();
    int idAgenda = Convert.ToInt32(gridProfissional.CurrentRow.Cells[0].Value.ToString());
    listaData = modelOff.data.Where(p => p.idAgenda.Equals(idAgenda)).ToList();
    gridData.DataSource = listaData;
    gridData.Select();
}

Minha intenção é a seguinte: ao selecionar uma linha no gridProfissional, chamar a função preencherGridAgenda e atualizar o gridAgenda.
No evento Scroll do gridProfissional eu estou chamando a função preencherGridAgenda, porém, eu seleciono qualquer linha do meu gridProfissional e a função não é chamada.
Estou usando o evento errado (Scroll)? Tem outro evento próprio pra isso?
Answer: A melhor forma de fazer isso é usando o evento SelectionChanged do DataGridView


Como delimitar uma campo string para uso na cláusula IN

Question: Na tabela_A possuo um campo cod_canal onde é um INT, na tabela_B possuo um campo canais do tipo string e que separa os códigos por ,.
Exemplo: 1,3,6,9,12.
Numa primeira tentativa, pensei apenas em fazer a cláusula da seguinte maneira:
[...] WHERE tabela_A.cod_canal IN (tabela_B.canais) [...]
E obviamente, recebi o erro:

SQL Error [245] [S0001]: Conversion failed when converting the
  nvarchar value '0,1,3,5,9,12' to data type int.
  com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed
  when converting the nvarchar value '0,1,3,5,9,12' to data type int.

Tentei utilizar a função PATINDEX, porém acredito não ter entendido o funcionamento correto dele e não tenho o resultado esperado
AND PATINDEX('%' + CAST(tabela_A.cod_canal AS NVARCHAR) + '%', tabela_B.canais) > 0

Como eu posso obter os resultados da tabela_B a partir do relacionamento entre os campos cod_canal e canais? Visto a diferença do tipo dos dados e formatos inseridos nos respectivos campos.
Comment: Você vai ter que converte para um array de inteiros
Answer: Você tem que converter sua string para uma list, para isso seria necessário uma FUNCTION para ser usada dentro do seu select.
create FUNCTION [dbo].[fnStringList2Table]
(
    @List varchar(MAX)
)
RETURNS
@ParsedList table
(
    item int
)
AS
BEGIN
    DECLARE @item varchar(800), @Pos int

    SET @List = LTRIM(RTRIM(@List))+ ','
    SET @Pos = CHARINDEX(',', @List, 1)

    WHILE @Pos > 0
    BEGIN
        SET @item = LTRIM(RTRIM(LEFT(@List, @Pos - 1)))
        IF @item <> ''
        BEGIN
            INSERT INTO @ParsedList (item)
            VALUES (CAST(@item AS int))
        END
        SET @List = RIGHT(@List, LEN(@List) - @Pos)
        SET @Pos = CHARINDEX(',', @List, 1)
    END

    RETURN
END

E chama da seguinte forma.
SELECT      *
FROM   tabela_A.cod_canal IN (SELECT item from fnStringList2Table(@statuslist))


Parent Publication option is not shwoing

Question: I am not able to add parent publication.I have create the the blank publication and create the root structure group. after that i want to inherit with my parent publication but no option is coming when i open the blur printing. Only child publication option is coming and disabled.
Comment: Hi Shekhar. You might want to ask this over at the Tridion Stack Exchange site: http://tridion.stackexchange.com/
Answer: You'll need to create the root structure group before being able to set it as a parent


kvm process has too large a memory footprint on host

Question: I'm using latest ubuntu quantal and start a kvm guest which should have 2048 MB of memory. Now after a few hours I can see that the kvm process of this guest is around 2700 MB, so 700 MB more than the guest should be able to consume. I mean a small overhead like 1% would be ok, but not 30%?!
<code>root      8631 74.0 22.2 4767484 2752336 ?     Sl   Nov07 512:58 kvm -cpu kvm64 -smp sockets=1,cores=2 -cpu kvm64 -m 2048 -device virtio-blk-pci,drive=drive-virtio0,id=virtio0,bus=pci.0,addr=0xa,bootindex=100 -drive file=rbd:data/vm-disk-1,if=none,id=drive-virtio0,cache=writeback,aio=native -device virtio-net-pci,netdev=net0,bus=pci.0,addr=0x12,id=net0,mac=02:7a:86:e6:1a:6c,bootindex=200 -netdev type=tap,id=net0,vhost=on -usbdevice tablet -nodefaults -enable-kvm -daemonize -boot menu=on -vga cirrus
root      8694  0.0  0.0      0     0 ?        S    Nov07   0:00 [kvm-pit/8631]
</code>
How is this possible and how to prevent it?
Answer: You could use the virtio balloon device to try and return memory to the system but this only helps if the guest OS is not using all of its memory
KVM does need some memory for itself to run, but I believe a lot of this gets swapped out after a while
Also, if you end up running lots of similar VMs make sure you have linux same page merging enabled. This will allow memory from similar VMs to be shared; takes more CPU usage up, but is worth it with lots of VMs. I think this is on now by default in ubuntu
Answer: One possible problem can be that you use cache=writeback on your drive. that can eat some of your memory apart from the memory used by the guest.
Haven't had time to verify if this is the case, but it's a guess.
Comment: When I change the command line from `cache=writeback` to `cache=none` it doesn't change anything.. :(


Rails 3, MongoId & bson version problem

Question: I just updated to Rails 3 final. Now I'm having problems with MongoId, Mongo's Ruby driver & bson. When I try to run Rails, I get "You have already activated bson 1.0.7, but your Gemfile requires bson 1.0.4. Consider using bundle exec. (Gem::LoadError)".
MongoId requires bson_ext 1.0.4 so I have gem "bson_ext", "1.0.4" in my Gemfile. I tried to uninstall bson 1.0.7 but then Rails failed to start because Mongo Ruby driver requires bson >= 1.0.5.
So any ideas how I can get this solved?
Comment: After 3 hours of pain and misery I solved this. I had require 'mongo' in my Gemfile because in Rails 3 rc2 this was required in order for mongodb to work but now it seems to break it. So I removed the line and now everything loads up.
Answer: this combination works for me:
<code>gem 'rails',     '3.0.6'
gem "mongoid",   "2.0.0"
gem "bson",      "1.2.4"
gem "bson_ext",  "1.2.4"

gem "devise" ,   "1.1.6"
</code>

Rails 3, MongoId & bson version problem


Read permission of installed Application in android phone?

Question: I want to read permission of other applications installed in my android mobile  using programming.
I think Android Cleaner  read permission of other apps and display details like

I want get detail like this Image.
In this it's give details of Ad Network
How i get details like this app in my app?
If this app not Read Permission then How it's do it?
Answer: Well you can scrape the playstore app page for a given app and get the permissions it needs :)
Well that's just off the top of my head. On a serious note, you can do the following:
<code>Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List appsList = getPackageManager().queryIntentActivities(intent, 0);

for (Object app : appsList) {
    ResolveInfo resolveInfo = (ResolveInfo) app;
    PackageInfo packageInfo = null;
    try {
        packageInfo = getPackageManager().getPackageInfo(resolveInfo.activityInfo.packageName, PackageManager.GET_PERMISSIONS);
    } catch (NameNotFoundException ex) {
        ex.printStackTrace();
    }

    String[] requestedPermissions = packageInfo.requestedPermissions;
}
</code>
Comment: i don't want to get permission of this app. but i want to get permission use by all apps
Comment: That's what I meant. Query the installed apps, get their package name and construct the playstore listing URL and scrape.
Comment: how i do it  ?  i already got all package name. but how i construct with playstore?
Comment: it's i know but i want details in offline mode


Want a select option of a field saved in another form

Question: i have a web form having following fields for sales department:
client name(text field), quarter(select option), countries(select option), Annual fees(number), Monthly fees(number), setup(fees)......
now i want to create a form in which i can have a list of all the client saved by above form
 for management to allot resources for the client
please suggest any module required or coding which required.
need help urgently on this
Answer: The module is Webform Views Select.
This question is related to this question.
Webform select option list from another submission data


Determining characteristics of peaks after mclust finite mixture model

Question: I'm working with the mclust package in R (specifically using densityMclust). As output, I have a file with mixing probabilities, variances, and means for each normal distribution. The general format is:
foo prob1 var1 mean1 prob2 var2 mean2...
foo2 prob1 var1 mean1 prob2 var2 mean2...

for as many normal distributions as I can force.
This is all I have; I don't even have access to the actual raw data. My goal is to identify relative maximas (peaks). Would I go about doing this by finding the largest means?
I have a few more questions:

I'm having trouble understanding what exactly a mixing probability is. If anyone could please direct me to a resource that I couldn't find, I'd really appreciate it.
Since I only have the 3 data types listed above, how would I find standard deviation values without the range of raw data values?
And also any better description for a Gaussian finite mixture model than mine: forces data into multiple bell curves...?
Why are these mixture models called unsupervised learning? All the explanations I bumped into online were way too technical for me.
As shown in the data above, I often have >2 peaks. However I'm only concerned with the first two. Can I ignore the rest and safely call that part a bimodal distribution?
Comment: Please don't cross-post.
Comment: This question isn't very clear. Can you post your data? Even if it isn't the raw data, it would help. What are "foo" & "foo2", outputs from Mclust from 2 different input datasets? What do you want the SDs of, exactly? You are given variances of the clusters. Are you aware that $SD=\sqrt{\rm Var}$?
Comment: I've deleted the duplicate post that someone migrated from Stack Overflow.
Comment: I can't post the data because it is proprietary. However I can be a bit more clear. I'm working with gene expression data, so foo and foo2 would be the names of some genes. I've clustered the actual expression data using a GMM and basically right now I have metadata for each subpopulation bell curve. As mentioned in the original question, I have mean, mixing probability, and variance.
Comment: @gung Correct me if I'm wrong - To find the peaks, take the relative maximums of the mean. To find the SD, take the square root of variance. I'm only interested in the first two peaks in expression level for each gene, so I can ignore the rest of them. The first two peaks form a bimodal distribution... And then I have some basic questions. (1) In layman's terms, what is a Gaussian FMM? (2) Why are mixture models called unsupervised learning? (3) In layman's terms, what is a mixing probability? Thanks.
Answer: Your questions (reposted so I can be systematic and complete) with my answers inline follow:
Question1: I'm having trouble understanding what exactly a mixing probability is. If anyone could please direct me to a resource that I couldn't find, I'd really appreciate it.
Answer1:
Sweet and salty can go great together.  So lets say you have a pretzel that you want to sprinkle a mix of salt and sugar over.  Do you HAVE to do 50/50?  No way.  You can vary it from 1 molecule of salt and a spoon of sugar all the way to 1 molecule of sugar and a spoon of salt.  The weights sum to 1.0 and really make up the proportions of the mix.  If you have two components and the first weight is 0.00001 and the second is 0.99999, that means the first is only slight and the second is huge.
For most ML things, I love autonlab.  Here is their materials on mixture models. (link).  This stuff tends to be pretty good.
Question 2: Since I only have the 3 data types listed above, how would I find standard deviation values without the range of raw data values?
Answer 2:
You can back it out of the parameter.  Here is the documentation for mclust. (link) Reading through it, while booring, can also be highly informative.  The first thing to try is the "summary" command.
est <- mclust(.... stuff ...)
summary(est)

If the parameter values show up in the displayed summary, then they are 1) stored somewhere, and 2) able to be extracted.
The fact that this selects the model with best parameters (link) means that they can be accessed.  I recommend you read through the documentation - it is in there.  I also recommend you use "Rstudio" because it has a variable explorer that allows you to look at fields and sub-fields of the "est".
Question 3. And also any better description for a Gaussian finite mixture model  than mine: forces data into multiple bell curves...?
See the link in answer 1 for Autonlab.  A finite mixture model is a linear weighted sum of probability densities.  A gaussian mixture, implicitly homogenous, is comprised as a weighted sum of Gaussian distributions.  There are non-Gaussian mixtures.  There are non-homogenous mixtures.  I particularly like the Zero Inflated Poisson by Diane Lambert.  I felt it was quite revolutionary in thought and valuable in application - allowing yield to be pushed closer to unity than a homogenous model and much of the thought at the time of publication.
Question 4. Why are these mixture models called unsupervised learning? All the explanations I bumped into online were way too technical for me.
You pick "number of components" and click and it goes.  That is unsupervised.  If you knew something about classification, and that was part of the input, then it would qualify as supervised.
Question 5. As shown in the data above, I often have >2 peaks. However I'm only concerned with the first two. Can I ignore the rest and safely call that part a bimodal distribution?
Throw away results only when you know why you are doing it.  Whether or not you realize it, you are doing voodoo and not science.  You don't know why it works, and if you did it twice you might get radically different results.  Science is about knowing "why" before doing.  It is about repeatable results.
In production, after we had root-caused one of the modes, only then could we focus on the other.  If you spent time to get input data, and you knew what you were doing when you specified mode count (aka number of components) then throwing one out without a good reason is a bad idea.
That said, you could look at the weights and make an argument like 95% of the weight is in the first 2 modes, so I am going to focus on them.  Management who doesn't realize how stunningly bad of an idea it is, will often let themselves fall prey to arguments like 80/20 rule - therefore I'm only retaining 80%.  Remember that they are the technical illiterate (aka non-technical) and you are serving them quite poorly - not doing due diligence in your area of expertise - if such things are allowed to occur.  Math, Statistics, Data-analysis folks - we are the guardians of truth.  Not religious or political truth but actual "the universe is speaking" truth.  If you get loose with what you know or what you don't then you are doing a bad job, and you are defacing the hard work and excellence of your peers in the field.  Don't do it.  Being ruthlessly aggressive about what you don't know and do know - never letting a hint of falsehood pass your lips - is how to build a great credibility and how to make a career worth having.  Don't be an ass to folks - but be as excellent as you are capable of in your work.
Best of luck
Comment: Beautiful answers to all my questions, and thanks for some great links as well! Appreciate your help.


Run flutter app on multiple connected devices/emulators simultaneously

Question: How can I run my flutter app on multiple devices at the same time without having to go through the sequential procedure of: select a device -> run, select other device -> run, etc.?
Using:
Android Studio 3.2.1
Flutter 1.0.0
Dart 2.1.0
Comment: Does this answer your question? [Flutter Hot Reload to multiple devices](https://stackoverflow.com/questions/51669258/flutter-hot-reload-to-multiple-devices)
Comment: It does. Don't know why I didn't find this question back then.
Answer: Run command in terminal:
flutter run -d all

or create a script (e.g. runall.sh in root):
#!/usr/bin/env bash
flutter run -d all

and go to "Run" -> "Edit Configurations". Press "+" in upper left corner -> select "Bash". Then set:

Name: runall
Script: [path to runall.sh script]
Interpreter Path: /bin/bash

Select "runall" instead of "main.dart" beside run icon. Performing run (also through shortcut) will now run app on all devices.
Drawback:  You'll have to enter "r" followed by Enter in run terminal for hot reload. Icon and shortcut does not work. Hot reload is performed on all devices though.
Just a workaround for now. I'm pretty sure the flutter plugin will cover this soon.
Answer: There are many ways to do this as previously answered. If you use VS Code instead of Android Studio as your Flutter IDE, this is how you can use the VSC launch configuration and tasks to run concurrently from a single launch and have hot reload enabled for all devices.
If you have an issue with executing flutter run -d all this is an alternative solution will which let you specify the devices that should run.
Ensure that the devices you specify are available when running flutter devices.
Your current launch.json file may look something like this:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Flutter",
            "type": "dart",
            "request": "launch",
            "flutterMode": "debug"
        }
    ]
}

Setup
You will need to update this launch.json file and create tasks.json in the same .vscode folder that is in your application's root directory.

Paste only the below code into launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Flutter-All",
            "preLaunchTask": "Flutter-Launch-All",
            "type": "dart",
        },
        {
            "name": "Flutter-iOS",
            "preLaunchTask": "Flutter-Launch-iOS",
            "type": "dart",
        },
        {
            "name": "Flutter-Android",
            "preLaunchTask": "Flutter-Launch-Android",
            "type": "dart",
        },
        {
            "name": "Flutter-Web",
            "preLaunchTask": "Flutter-Launch-Web",
            "type": "dart",
        }
    ],
}

Paste only the below code into tasks.json
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Flutter-Launch-All",
      "dependsOn": [
        "Flutter-Launch-iOS",
        "Flutter-Launch-Android",
        "Flutter-Launch-Web"
      ]
    },
    {
      "label": "Flutter-Launch-iOS",
      "type": "shell",
      "command": "flutter run -d 'iPhone 11' "
    },
    {
      "label": "Flutter-Launch-Android",
      "type": "shell",
      "command": "flutter run -d 'AOSP on IA Emulator' "
    },
    {
      "label": "Flutter-Launch-Web",
      "type": "shell",
      "command": "flutter run -d 'Chrome' "
    }
  ]
}

Replace the device names accordingly ('iPhone 11', 'AOSP on IA Emulator', 'Chrome').
Firing up all devices
Press the F5 key.
And you're done.
If the F5 shortcut to Start Debugging does not work for you, navigate to Debug & Run on the side panel and select the Flutter-All Configuration you've just created and then Run.

You will then see the terminal window appear and will able to switch between the individual hot-reload sessions running (as Tasks in their own shell).

Some Background
We use 'Compound Tasks' by way of the dependsOn option on a Task and not 'Compounds' which are for Configurations.
As it is not possible to launch Configurations concurrently, only sequentially, we use tasks which can run concurrently.
Hence, the "Flutter-All" Configuration executes the tasks of the iOS, Android and Web Configurations.
If using Compounds, a Configuration will need to complete before the next runs which is not what we want.
With Tasks we can choose to execute them sequentially however by default they will execute concurrently when using the dependsOn option.
//Do not use this unless you want to use Configurations only by testing them sequentially and not tasks
"compounds": [
    {
        "name": "Flutter-All",
        "configurations": ["Flutter-iOS", "Flutter-Android", "Flutter-Web"],
    }
]

Answer: If you don't want to use the command line directly each time, you can do the following workaround:

Download bashsupport plugin (link)
Create new configuration of bash, leave the script field empty, and in the interperter options cell insert:flutter run -d all. It should look something like:
If step two didn't work, create a file call something like run_all.sh in your root project. and put the next lines there(assuming that bin/bash is the path to your bash):
#!/bin/bash
flutter run -d all
type in your terminal:chmod 755 run_all.sh.
Specify run_all.sh in your configuration and bin/bash as your interprter path.
Remove flutter run -d all from interperter options.
It should look something like:
Answer: You can always have an external tool watch the files for you and trigger a hot reload.
Flutter supports certain signals to trigger a hot reload natively
  --pid-file  Specify a file to write the process id to. You can send SIGUSR1 to trigger a hot reload and SIGUSR2 to trigger a hot restart.

Here is an fast example:
#!/usr/bin/env bash

set -euo pipefail

# Remove previous pid files
rm -f /tmp/flutter.pid

# Run in a loop a hot reload call in a subshell
(while true
do
    # Wait for flutter to start before monitoring pid
    while [[ ! -f /tmp/flutter.pid ]]; do sleep 1; done;

    # Send hot reload signal when files change
    find lib/ -name '*.dart' | entr -n -d -p kill -USR1 $(cat /tmp/flutter.pid)
done) &

# Run all devices under 1 pid
flutter run -d all --pid-file /tmp/flutter.pid

Idea from: https://medium.com/@kikap/how-to-automatically-hot-reload-flutter-when-dart-source-files-change-6e8fdb523004
For more details on entr: http://eradman.com/entrproject/entr.1.html


UIScrollView with UITableView / UICollectionView zooming issue

Question: What i want to achieve :
I want to creating scrolling list of images like a comic strip where i should be able to provide pinch and zoom. It can contain 100 images.
What i have tried :

UIScrollView -> UIView -> UIImageView : The problem in this approach is that i get the zooming effect but the time taken to create the strip is around 5 sec and the memory consumption of the app becomes high.
UIScrollView -> UIView -> UITableView -> UITableViewCell -> UIImageView : This resolves loading issue , memory issue . But the problem is with Zooming . I cannot achieve the same effect of Zooming on UITableView. I added the pinch gesture on the UITableView it zooms and scrolls vertically but horizontal effect is not achieved.
UICollectionView -> UIImageView : This also resolves loading issue , memory issue but has same problem with zooming as it zooms a particular cell but after zooming to certain effect the cell disappears . And its also not uniformly applied to all UICollectionViewCells.

Any reference or code or idea's really appreciated.
Comment: Just an idea: I wouldl try to use the first option but using images with poor quality and replace this images  when the scrolls gets closer
Answer: It seems like the problem with option 1 is that you are loading all 100 images at once when the view loads.
If that is the case you could reduce the number of images you keep loaded in memory to a small amount.
For example just load 5, the image being viewed, 2 before it in the list and the 2 that come after it. When the user views the next image in either direction update the loaded images.
Answer: I'm developing an application that it likes what she said.

<code>//初始化ScrollView
        let scrollView = PalyView.init(frame: UIScreen.main.bounds)
        scrollView.minimumZoomScale = 1
        scrollView.maximumZoomScale = 2
        scrollView.delegate = self
        self.view.addSubview(scrollView)

        //初始化_collectionView
        _collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height * 5), collectionViewLayout: _layout)
        _collectionView?.backgroundColor = UIColor.white
        _collectionView?.delegate = self
        _collectionView?.dataSource = self
        _collectionView?.showsVerticalScrollIndicator = false
        _collectionView?.contentInset = UIEdgeInsetsMake(0, 0, 6, 0)
        _collectionView?.register(WaterCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        scrollView.addSubview(_collectionView!)</code>


View is removing iframe from custom text

Question: I'm using a global custom text field within a view that is meant to display an embedded youtube video.

However in the actual render of the view it's completely removed from the dom.
My first assumption was that ckeditor was not allowing the iframe tag and removing it itself. However I have it setup to allow iframe tags, and if I go back and edit the Global Custom text it still appears. If it didn't allow it I'm assuming it would not appear in the editor the next time I open and edit the field.
Also I'm able to embed iframes in the body text of nodes just fine. It's specifically in views.
I also attempted creating iframes with different src's in different divs but I still had the same behavior.
Are there other possible causes of Drupal removing iframes from custom text in views? Is this the expected behavior? If this is the expected behavior is there away around this?
EDIT: Forgot to mention that 'Strip HTML tags' is also turned off.
Answer: This is not the expected behavior of drupal views, Drupal Views usually not doing this.
I have done this before, and global text with iframe is working with no issue.
Maybe you have another issue like some javascript issue to prevent the load iframe form another site, see the console of your webpage maybe you got some error.
You can debug also by putting that iframe into any page Textarea field where you already use the HTML content of your website.
Answer: Check in the view preview whether the iframe shows there. If it does, your issue is with your theme, most likely, or some module, but not Views.
Comment: It does not show up in the view preview


Positive expected value for lottery

Question: As far as I know, to decide either you should enter a bet or not, you should get the expected value of that bet
I was wondering if the lottery has a very high expected value, is it wise to join?
There is a real life lottery with this inputs
Choose 5 numbers out of 50
If you get 3 right you win 350
If you get 4 right you win 1000,000
If you get the 5 numbers right you win 10,000,000
Entry fee is 35
So Expected value is

so total of 112.5- 35(entry fees) = 77.5
This is a very high expected value, i wonder if i did the math wrong?
it was like simple probability
3 winning balls should be
(combin(5,3) * combin(45,2)) /combin (50,5)
And so on
did I  calculate it wrong? or it's just too good ?
and if the expected value is more than double the entry fees, is wise mathematically to join for a long run?
Noting that for i know that for even wining 4 numbers, probability to lose is 99.989%
on the long run for 52 times for example, the probability to lose them all is 99.989%^52 = 99.449%
I'm just confused how the expected value is too high, yet by intuition it seems the right decision is not to join even for a long run
Or how should I think about it?
Edit :
I guess the point is the 1 Million prize will be shared between winners, but i don't know how should i calculate the expected value in that case?
Comment: Real-life lotteries are always designed to have negative expected value for players. That's because the goal of running a lottery is to make money for those who run it.
Comment: I second @paw88789's request. Since the primary contributor to the expected value, by a large margin, is the $4$-out-of-$5$ event, I wonder if the payout was supposed to be $100,\!000$ instead of $1,\!000,\!000$.
Comment: Can you give a source for the details of this lottery?
Comment: This is a real lottery, but i guess i understood the trick

the million will be split between the winners, so i shouldn't have multiplied by 1 million, yet  i don't know how to expect how many people will share this to be able to calculate the expected value
Comment: This was an unfortunate migration.
Answer: I simplify the lottery a little bit. Let's say the players can win a fix prize $W$, no matter how many players participate in the lottery. We do not regard any fee. Each player can win this prize with a probability of $p$. If n players win, then the prize is equally distributed among the players. W.l.o.g. we calculate the expected value for 2 players. They win in total $W$ if at least one of the players win. Thus the expected value is
$$E^{(2)}(W)=W\cdot \left( p^2+2\cdot p\cdot (1-p)\right)=W\cdot (1-(1-p)^2)$$
We can generalize the result
$$E^{(n)}(W)=W\cdot (1-(1-p)^n)$$
Now the fix prize W has to be equally distributed amoung the $n$ players. Thus the expected value for one player is $E^{}(W)=\frac{W}n\cdot (1-(1-p)^n)$. We can look at some interesting values.

$\lim\limits_{n\to \infty} \frac{W}n\cdot (1-(1-p)^n)=0$. If
(theoretically) the number of players goes to infinity the expected
value is $0$.

If only one player participate at the lottery then the expected value is $W\cdot (1-(1-p)^1)=p\cdot W$.

If the prize W is increasing in some way by the number of players $n$, then this can be taken into account.
Answer: The expected value calculation when the pot gets to ~$20$ million or more has to take into account the returns from investing the winnings. If you win a pot of $20$ million and get about $10$ million after tax (being ver conservative about the tax rate here), you could reasonably expect to earn $4\%$ per year, which is $400$k per year. If you are financially responsible, a win $20$ million is enough for you and your kids to be financially independent.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Positive expected value for lottery


How to find the origin of variable in Drupal

Question: Maybe this a compound question, please bear with me: I need to find out why the meta tags are not being printed on the homepage of a theme. The problem is that in html.tpl.php I've got this line: <?php print $head; ?>.
In other pages, the meta tags are being printed ok, but not on the homepage. When I look at the page--front.tpl.php it doesn't include any header info or markup (only the markup from the menu downwards and I can't figure out:

Why the difference and;
Where is the $head being defined.

And yes, the content of the homepage does have tags added to it.
Can anyone point me in the right direction?
Answer: Looks like you should debug the code not in theme but in the module.
I assume you use the metatag module. It adds all the metatags in metatag_html_head_alter().
Check what is your front page. If it is a View of a Panel, metatags are handled in a different way.
In the metatag module you can specify separate tags for the front page - check this setting. It might override your content metatags.


increase download speed for users via nginx

Question: Is there a setting with nginx that could be restricting or limiting the download speed of my users? My users are getting around 300kb/s If I use a download accelerator and download a file simultaneously I max out my internet at 1.2 mb/s. My conclusion is that somehow nginx is restricting my download speed. My site does not get heavy traffic, so I don't know why I'm getting such slow speed.
Any ideas what could cause the slow downloads?
<code>http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    client_max_body_size 64M;
    access_log  off;

    sendfile        on;
    tcp_nopush     on;

    keepalive_timeout  5;

    server_tokens off;

    gzip  on;
    gzip_comp_level 5;
    gzip_proxied any;
    gzip_min_length 1280;
    gzip_buffers 4 8k;
    gzip_types      text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    # Load config files from the /etc/nginx/conf.d directory
    include /etc/nginx/conf.d/*.conf;

}
</code>
Comment: Thus the nature of the internet, it's not nginx limiting you.
Comment: Check if sendfile is installed. It must be activated and installed to run.
Answer: Okay, you've got some weird comparisons going on here.
First: Are your users using download accelerators? If not, then your tests with one are meaningless.
Second: Where are your users in relation to the server?  Where are you in relation to the server?  If your users are significantly further away then you are, this could be causing slow speeds.  If they are on a different ISP than you, your tests just prove it's not an issue with the server nor your path to the server.
Third: Do your users experience the slow downloads only sometimes?  For example, if they try during peak times (generally sometime between 6PM-2AM) and have slow speeds, but have significantly increased speeds if they try off-peak this would indicate a capacity issue somewhere along the way.
Fourth: You're on a VPS, when your users report the slow speeds did you test immediately?  It's possible that someone else on the same physical machine as you is doing something very bandwidth/cpu intensive.
Nginx is probably not the cause here.  Did you talk to your provider?  They would really be in a better position to answer your questions then we are.


Validate form on button click in angular

Question: As I am new in angular 4.0 and I am stuck at the validation
I am having a form which consists two fields
here is the form
<form action="my-account.html" method="post" class="form-horizontal">

                User name

                <input type="email" class="form-control" id="exampleInputEmail1"  placeholder="Username" required>

                Password

                    <input type="password" class="form-control" id="exampleInputPassword1"  placeholder="Password" required>

                    <button type="submit" class="btn btn-primary btn-sm"  [routerLink]="['/dashboard']">Submit</button>
                    <button type="submit" class="btn btn-primary btn-sm">I Forgot My Password</button>

        </form>

I want to do validation on a submit button
**<button type="submit" class="btn btn-primary btn-sm"  [routerLink]="['/dashboard']">Submit</button>**

In the simplest way so how can I do it?
Comment: Might help: https://angular.io/guide/form-validation
Answer: Use this link and go through explains the whole scenario for validation
https://www.toptal.com/angular-js/angular-4-forms-validation
<form (ngSubmit)="onSubmit(loginForm)" [formGroup]="loginForm" novalidate class="form-horizontal">

      User name

      <input type="email" formControlName="username" class="form-control" id="exampleInputEmail1"  placeholder="Username" required>

      Password

          <input type="password" formControlName="password" class="form-control" id="exampleInputPassword1"  placeholder="Password" required>

          <button type="submit" class="btn btn-primary btn-sm"  [disabled]="loginForm.$invalid">Submit</button>
          <button type="submit" class="btn btn-primary btn-sm">I Forgot My Password</button>

</form>

//and in you .ts file
 constructor(private fb: FormBuilder){}

ngOnInit() {
    this.profile = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]]
    })
};

Comment: loginForm: FormGroup; in the beginning and replace this.profile with this.loginForm
Comment: when i am trying to apply [formgroup] tag in  form control then it is showing error like template parsing error
Comment: you have to include formsModule in app.module.ts
Comment: also go through the above link i have mentioned it carries all information step by step.
Comment: even if you stuck somewhere please post
Comment: we need to import ReactiveFormsModule in app.modules to avoid this problem.
Comment: No, FormsModule from angular forms


difficulty modifying two dimensional ruby array

Question: Excuse the newbie question. I'm trying to create a two dimensional array in ruby, and initialise all its values to 1. My code is creating the two dimensional array just fine, but fails to modify any of its values.
Can anyone explain what I'm doing wrong?
  def mda(width,height)
     #make a two dimensional array
     a = Array.new(width)
     a.map! { Array.new(height) }

     #init all its values to 1
     a.each do |row|
       row.each do |column|
          column = 1
       end
     end
     return a
  end

Answer: It the line row.each do |column| the variable column is the copy of the value in row. You can't edit its value in such way. You must do:
def mda(width,height)
  a = Array.new(width)
  a.map! { Array.new(height) }
  a.each do |row|
    row.map!{1}
  end
  return a
end

Or better:
def mda(width,height)
  a = Array.new(width)
  a.map! { Array.new(height) }

  a.map do |row|
    row.map!{1}
  end
end

Or better:
def mda(width,height)
  a = Array.new(width){ Array.new(height) }
  a.map do |row|
    row.map!{1}
  end
end

Or better:
def mda(width,height)
  Array.new(width) { Array.new(height){1} }
end

Comment: Are 'width' and 'height' mixed up? Also, this can be done without blocks:  Array.new(height, Array.new(width, 1))
Comment: @steenslag, No, it can't. If you are building multi-dimensional array in such way, when you assign value to one element of it, it will be spread to the whole column. It would be like `array = [[1]*w]*h`, where you will just make `h` copies of the *pointer* to the same 1-dimensional array. About mixing of `width` and `height` — it is another question, which was not supposed to be discussed by author.
Comment: P.S.: see ghostdog74's answer. It must have at least one block.
Answer: each passes into the block parameter the value of each element, not the element itself, so column = 1 doesn't actually modify the array.
You can do this in one step, though - see the API docs for details on the various forms of Array#new. Try a = Array.new(width) {|i| Array.new(height) {|j| 1 } }
Comment: No need to include block variables when they aren't being used.
Comment: I did not know that. I'd assumed they were like method params, and Ruby would complain if they were absent. Ah well - YLSNED!
Answer: you can create it like this?
a=Array.new(width) { Array.new(height,1) }

Answer: column in your nested each loop is a copy of the value at that place in the array, not a pointer/reference to it, so when you change its value you're only changing the value of the copy (which ceases to exist outside the block).
If you just want a two-dimensional array populated with 1s something as simple as this will work:
def mda(width,height)
  [ [1] * width ] * height
end

Pretty simple.

By the way, if you want to know how to modify the elements of a two-dimensional array as you're iterating over it, here's one way (starting from line 6 in your code):
 #init all its values to 1
 a.length.times do |i|
   a[i].length.times do |j|
     a[i][j] = 1
   end
 end

Comment: See comments under Nakilon's answer: this array creation does not work (try to change one of it's values).


how to ser read unread message in custom listview in android

Question: i have one Custom list view in android in which i set base adapter, in one row of custom list view i have two texview. now i set the text of these two textviews from json parsing. i want to display read unread messages. how can i achieve this?
following is my code for adapter class,
public class ImageAdapter_Notification extends BaseAdapter
{

    //Serch
    Context mContext;
    LayoutInflater inflater;
    //Serch

    String[] message;
    String [] id;
    String[]date;

public ImageAdapter_Notification(Context context)
{
    mContext = context;
    inflater = LayoutInflater.from(mContext);
}

public ImageAdapter_Notification(Context context,String [] message, String [] id,String[]date)
{
    mContext = context;
    inflater = LayoutInflater.from(mContext);
    this.message=message;
    this.id=id;
    this.date=date;

}

public class ViewHolder {
    TextView txt_top,txt_large,txt_date;

}

public int getCount() {
    //return array_str_logo.length;
    return message.length;

}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return position;
}

    public View getView(final int position, View convertView, ViewGroup parent)
    {

        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();

            convertView = inflater.inflate(R.layout.custom_notification, null);

            // Locate the TextViews in listview_item.xml

            holder.txt_top = (TextView) convertView.findViewById(R.id.txt_top);
            holder.txt_large=(TextView) convertView.findViewById(R.id.txt_large);
            holder.txt_date=(TextView) convertView.findViewById(R.id.txt_date);

            // Locate the ImageView in listview_item.xml
            convertView.setTag(holder);
        }
        else {

            holder = (ViewHolder) convertView.getTag();
        }
        // Set the results into TextViews
    /*  if(position%2==0)
        {
        holder.txt_top.setTextColor(Color.RED);
        }else
        {

        }
    */  holder.txt_top.setText(id[position]);
        holder.txt_large.setText(message[position]);
        holder.txt_date.setText(date[position]);

        convertView.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent intent=new Intent(Notification_Activity.this,Notification_Details.class);
                intent.putExtra("from", id[position]);
                intent.putExtra("message",  message[position].toString());
                intent.putExtra("date",  date[position].toString());
            //  Log.i("message", message[position].toString());
                startActivity(intent);

            }
        });

        return convertView;
    }

}// End of ImageAdapterclass

how can i text color for read- unread message.
any help would be appreciated heartly.
Comment: I hope those messages are coming from a database, aren't they?
Comment: no data are coming from server through json parsing.
Comment: On server side, is there a database to save messages?
Comment: @Nizam...yes there is a database to save messages
Answer: If you have a database at server side to maintain messages, then adding an extra column for this purpose will solve the problem. Say, column Status Integer Default 0
Now, inside your getView(), check this value and set corresponding color.
When user reads the message, change the value in the table to 1.
Comment: you mean to say if user read message at that time android app should post something which updates the status in database? if so then that message will automatically consider as a read for other users as well. isn't it?
Comment: So the message is not for a particular user?
Comment: No. For Every User who installs the app
Comment: Then you have to design another table (with foreign key) for this purpose. And for each user, there should be an entry.
Comment: Thanks this will help me a lot.


Best way to store static values for use in Angular expressions?

Question: I have some static config-like values that are used throughout the web app. Currently I am creating directives to put them into the $scope, but that seems awfully wasteful.
Is there a way for angular expressions to directly access some kind of "static" values defined either in some module or in the Javascript global scope?
Comment: Show an example of what you want to store.
Comment: Similarly,you can use the constant in angularjs.

http://stackoverflow.com/questions/18494050/is-there-a-way-in-angularjs-to-define-constants-with-other-constants
Answer: First, consider if globals/statics are the way to go...
If so, define your statics as values in angular:
angular.module('globals', [])
    .value('serverConfig', 'xyz')
    .value('foo', { x:4, y: 5 })
    // etc

You can use those globals from code with normal dependency injection; use a run function to place them in the $rootScope, so that they are also available in expressions:
angular.module(...)
    .run(['$rootScope', 'serverConfig', 'foo', function($rootScope, serverConfig, foo) {
        $rootScope.serverConfig = serverConfig;
        $rootScope.foo = foo;
        // etc
    }]);

If you only need them available in expressions, just use the run() function.
Comment: Almost forgot about run blocks. This seems to be a nice way of bridging the two worlds. I think I'll create an object in the root scope as a "namespace" for static things.
Comment: Just implemented this. Worked very well. Thank you very much :)
Answer: You can use the constant in angularjs,it will be helpful.
module.constant(name, object);
or
module.value(name, object);
or
you can use localStorage in html5(It cannot store the object),for storing object use localStorageModule third party js
Comment: I know about constants but I don't see a way to access them from angular expressions?
Comment: Try to store in $scope of the current controller and access it. Or else go with the $rootscope


DELETE relation when using FOREACH in neo4j

Question: I need to DELETE relations of particular type of a node which is iterating over FOREACH.
In detail ::
PROFILE MATCH (n:Label1)-[r1:REL1]-(a:Label2)
WHERE a.prop1 = 2
WITH n
WITH COLLECT(n) AS rows
WITH [a IN rows WHERE a.prop2 < 1484764200] AS less_than_rows,
[b IN rows WHERE b.prop2 = 1484764200 AND b.prop3 < 2] AS other_rows
WITH size(less_than_rows) + size(other_rows) AS count, less_than_rows, other_rows
FOREACH (sub IN less_than_rows |
  MERGE (sub)-[r:REL2]-(:Label2)
  DELETE r
  MERGE(l2:Label2{id:540})
  MERGE (sub)-[:APPEND_TO {s:0}]->(l2)
  SET sub.prop3=1, sub.prop2=1484764200)
WITH DISTINCT other_rows, count
FOREACH (sub IN other_rows |
  MERGE(l2:Label2{id:540})
  MERGE (sub)-[:APPEND_TO {s:0}]->(l2)
  SET sub.prop3=sub.prop3+1)
RETURN count

As FOREACH is not suppoting MATCH, I used MERGE to achieve it. But it is very slow when I execute it (It is taking around 1 min).
But If I excete with out FOREACH (stop updaing), it is giving around 1 sec.
Problem:: Clearly the problem with FOREACH or inside operations with in FOREACH.
I want to delete a particular relation, create another relation and set some properties to node.
Note:: I showed total query because Is there any other way to achieve the same requirement (out of this FOREACH, I tried with CASE WHEN)
Answer: I noticed a few things about your original query:

MERGE(l2:Label2 {id:540}) should be moved out of both FOREACH clauses, since it only needs to be done once. This is slowing down the query. In fact, if you expect the node to already exist, you can use a MATCH instead.
MERGE (sub)-[:APPEND_TO {s:0}]->(l2) may not do what you intended, since it will only match existing relationships in which the s property is still 0. If s is not 0, you will end up creating an additional relationship. To ensure that there is a single relationship and that its s value is (reset to) 0, you should remove the {s:0} test from the pattern and use SET to set the s value; this should also speed up the MERGE, since it will not need to do a property value test.

This version of your query should fix the above issues, and be faster (but you will have to try it out to see how much faster):
PROFILE
MATCH (n:Label1)-[:REL1]-(a:Label2)
WHERE a.prop1 = 2
WITH COLLECT(n) AS rows
WITH
  [a IN rows WHERE a.prop2 < 1484764200] AS less_than_rows,
  [b IN rows WHERE b.prop2 = 1484764200 AND b.prop3 < 2] AS other_rows
WITH size(less_than_rows) + size(other_rows) AS count, less_than_rows, other_rows
MERGE(l2:Label2 {id:540})
FOREACH (sub IN less_than_rows |
  MERGE (sub)-[r:REL2]-(:Label2)
  DELETE r
  MERGE (sub)-[r2:APPEND_TO]->(l2)
  SET r2.s = 0, sub.prop3 = 1, sub.prop2 = 1484764200)
WITH DISTINCT l2, other_rows, count
FOREACH (sub IN other_rows |
  MERGE (sub)-[r3:APPEND_TO]->(l2)
  SET r3.s = 0, sub.prop3 = sub.prop3+1)
RETURN count;

If you only intend to set the s value to 0 when the APPEND_TO relationship is being created, then use the ON CREATE clause instead of SET:
PROFILE
MATCH (n:Label1)-[:REL1]-(a:Label2)
WHERE a.prop1 = 2
WITH COLLECT(n) AS rows
WITH
  [a IN rows WHERE a.prop2 < 1484764200] AS less_than_rows,
  [b IN rows WHERE b.prop2 = 1484764200 AND b.prop3 < 2] AS other_rows
WITH size(less_than_rows) + size(other_rows) AS count, less_than_rows, other_rows
MERGE(l2:Label2 {id:540})
FOREACH (sub IN less_than_rows |
  MERGE (sub)-[r:REL2]-(:Label2)
  DELETE r
  MERGE (sub)-[r2:APPEND_TO]->(l2)
  ON CREATE SET r2.s = 0
  SET sub.prop3 = 1, sub.prop2 = 1484764200)
WITH DISTINCT l2, other_rows, count
FOREACH (sub IN other_rows |
  MERGE (sub)-[r3:APPEND_TO]->(l2)
  ON CREATE r3.s = 0
  SET sub.prop3 = sub.prop3+1)
RETURN count;

Answer: Instead of FOREACH, you can UNWIND the collection of rows and process those. You can also use OPTIONAL MATCH instead of MERGE, so you avoid the fallback creation behavior of MERGE when a match isn't found. See how this compares:
PROFILE
MATCH (n:Label1)-[:REL1]-(a:Label2)
WHERE a.prop1 = 2
WITH COLLECT(n) AS rows
WITH [a IN rows WHERE a.prop2 < 1484764200] AS less_than_rows,
[b IN rows WHERE b.prop2 = 1484764200 AND b.prop3 < 2] AS other_rows
WITH size(less_than_rows) + size(other_rows) AS count, less_than_rows, other_rows
// faster to do it here, only 1 row so it executes once
MERGE(l2:Label2{id:540})
UNWIND less_than_rows as sub
OPTIONAL MATCH (sub)-[r:REL2]-(:Label2)
DELETE r
MERGE (sub)-[:APPEND_TO {s:0}]->(l2)
SET sub.prop3=1, sub.prop2=1484764200
WITH DISTINCT other_rows, count, l2
UNWIND other_rows as sub
MERGE (sub)-[:APPEND_TO {s:0}]->(l2)
SET sub.prop3=sub.prop3+1
RETURN count

Comment: cybersam had a good point about moving the MERGE of l2 from the loop. Even though my query doesn't have a FOREACH, I moved it above the UNWIND, so it only gets executed once on one row, instead of for every row after the UNWIND.


Name of property: $g(f(a), f(b)) = f(g(a, b))$

Question: What's the name of the property of the functions $f$ and $g$ that lets one do this:
$g(f(a),f(b))=f(g(a,b))$
For example, I'm looking for a certain class of functions that do this:
$f(a) \oplus f(b)=f(a \oplus b)$. In this case, $g$ is the binary XOR operator which also happens to be symmetric, but symmetry isn't necessary.
Sorry for the simple question that's probably been asked a million times, but it's hard to find the name of something of which one doesn't know the name. Thanks!
Comment: Depends on the context, but you can think of $f$ as a $g$-homomorphism, where you think of $g$ as a binary operation. Or you can similarly think of it as like a distributive law of $f$ over $g$. Not sure it has a name in general, however.
Comment: Your particular example is actually much, much nicer than the general case you're asking about. The binary strings form a vector space with XOR as addition (scalar multiplication is by 1 or 0 treated as integers mod 2) and $f$ is a linear transformation, hence representable by a matrix.
Answer: Even if $g$ has two and not just one inputs, one usually says "$f$ commutes with $g$", but I'd prefer "$f$ is a homomorphism (in fact: endomorphism) of the magma (or whatever structure it is)  $(X, g)$" (where $g\colon X\times X\to X$ and $f\colon X\to X$).


Help with my time series ARX model prediction?

Question: I have created an ARX-model where I predict the nitrogen oxide levels based on past values of nitrogen oxide with past exogenous input values nitrogen dioxide, temperature, atmospheric particulate matter, etc.
This might be a straightforward question, but I started to wonder if for example my ARX-model would be the following:
$$ Y_{t} = \alpha_{0} + \alpha_{1}Y_{t-1} + \alpha_{2}Y_{t-2} + \beta_{1}X_{t-1}^{1} + \beta_{2}X_{t-2}^{1} +  \gamma_{1}X_{t-1}^{2} + \gamma_{2}X_{t-2}^{2} + . . . $$
Where Y:s correspond to my past values of nitrogen oxide(NO) and the X:s correspond to different exogenous input values.
Now if I have data available until time t on all time series and I want to make predictions until say time t+10, won't I need to first predict all the future values of exogenous inputs? After I have predicted the exogenous values I can start to predict the NO-levels with my model correct?
So I'm predicting predictions with predictions? :)
I'm very new at this and my question might be stupid x) Please comment if my question is unclear
Answer: Yes, you will have to predict your predictors.  You can build a model for each of them and use the forecasts to drive your equations prediction.
Answer: I am no chemist, but I imagine that future values of nitrogen oxide (your target variable) could in part be determined by nitrogen *di*oxide... but also vice versa, so your target variable and your "exogenous" variable influence each other (so the "exogenous" variable would not be really exogenous any more). This might call for Vector Autoregression or similar models.


Vector subscript out of range - C++

Question: I am using visual studio 2013. I'm trying to get a subvector from a vector:
std::vector <Ponto> pontosDeControle;
std::vector<Ponto> subPontosDeControle;

the vector pontosDeControle is filled with some objects, then I get the subvector from position i to pontosDeControle.size()-1:
   subPontosDeControle = std::vector<Ponto>(&pontosDeControle[i], &pontosDeControle[pontosDeControle.size()]);

where i is less then pontosDeControle.size()-3.
This code is returning a debug assertion failed: Vector subscript out of range. However, on release mode works fine.
I'm not seeing the problem here.
Answer: In the debug mode the compiler checks that used index in this expression
pontosDeControle[pontosDeControle.size()]

is out of range.
You could write instead
subPontosDeControle.assign( std::next( pontosDeControle.begin(), i ),
                            pontosDeControle.end() );

It would be more clear and correct.
Answer: For a vector v with size v.size() you can only access indices 0...v.size() - 1 (of course, if v.siz() == 0 there is no accessible index). If you want to get a pointer to the element past the last one (you can get this address legally), you'd use something like this:
v.data() + v.size()

For the operations you want to use you don't need to use addresses of elements: you can use iterators instead:
subPontosDeControle.assign(pontosDeControl.begin() + i, pontosDeControl.end());

Vector subscript out of range - C++


How to graph quantitative and qualitative improvement in human health related measures?

Question: I'm creating an app that logs daily data from my users.
Data includes:

waist circumference, weight (Quantitative data)
certain conditions like psoriasis, migraines, fatigue (Qualitative data rated from 1 to 5).

Showing charts for each entitiy is fairly easy.

How can I take both data and show an overall improvement graph/chart based on each day?
Which type of graph/chart will work in this situation?

I'll be using google charts to visualize my data (i.e., see this this gallery of Google Charts).
Answer: You'll probably want to use something like a "Line Chart" with Google Charts, which conveys trends over time. The most direct way, in my mind, is to develop some sort of composite score. Something like "Wellness".
How I'd do this is to let each of your participants set a weight for each factor (how much they care about it), and then present a weighted average of their % change in each factor. If you don't want to deal with that much personalization, you could set the weights a priori.
This would probably work fine for individual data visualization, "Track Your Progress" type applications. You'd want something more sophisticated if you're intending to use it in a full blown study.
Answer: This is an interactive visualization of how world health and wealth data has changed over time. Something like this would be a great way to visualize human health improvements.
http://labs.infragistics.com/motion-framework/world-stats/
This is a Silverlight application built using data visualization controls from Infragistics (www.infragistics.com)
Disclaimer: I am a Technical Evangelist for Infragistics


Limit distribution of $\sqrt{n}(Y_n-e)$

Question: I'm trying to find limit distribution of $\sqrt{n}(Y_n-e)$ as $n \to\infty$, where:
$$Y_n=\left(\prod_{i=1}^n U_i\right)^{-1/n}$$
and
$U_i$ is i.i.d. uniform distributions in interval $(0,1)$.
My thinking so far is to use formula for uniform distribution product:
$$P_{U_1\cdots U_n}(u)=\frac{(-1)^{n-1}}{(n-1)!}(\ln u)^{n-1}$$
and then by using limit rules get the final solution.
However, I feel that the path I have chosen is very complicated and I wonder is there a more elegant solution?
Answer: The central limit theorem will give you the limit distribution for $\sqrt n ( \log Y_n - d)$ for some $d$ that depends on the distribution of $\log U_n$.  Then apply the ``delta method'' (to the function $x\mapsto \exp(x)$) to finish the job.

Limit distribution of $\sqrt{n}(Y_n-e)$


Connection and SqlServerConnection mismatch

Question: Apologies for terminilogy used.
I have a generic class that I want to use to fill JXComboBoxes.
It looks like this:
package Fillers;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.jdesktop.swingx.JXComboBox;

public class ComboBoxFiller {

    private Connection connConnection;
    private JXComboBox cboComboBox;
    private String strComboBoxQuery;

    public ComboBoxFiller(Connection connUToolDb, JXComboBox cboComboBox, String strComboBoxQuery) throws SQLException
    {
        this.connConnection = connUToolDb;
        this.cboComboBox = cboComboBox;
        this.strComboBoxQuery = strComboBoxQuery;
        Fill();
    }

    public void Fill() throws SQLException {
        ResultSet rsComboBox = null;
        PreparedStatement prepstmntComboBbox = null;
        try {
            prepstmntComboBbox = connConnection.prepareStatement(strComboBoxQuery,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rsComboBox = prepstmntComboBbox.executeQuery();
            cboComboBox.removeAllItems();
            while (rsComboBox.next())
            {
                String ComboBoxItem = rsComboBox.getString(1);
                cboComboBox.addItem(ComboBoxItem);
            }
        }
        finally {
            try {
                rsComboBox.close();
                prepstmntComboBbox.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

The Database I use is a SqlServer database. To connect to the database I use another generic class.
It looks like this.
package DbConnections;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcSQLServerConnection {

    private Connection connJdbcSqlServer;

    public void Connect(String dbURL) throws ClassNotFoundException {
        try {
            //DriverManager.registerDriver(new SQLServerDriver());
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            setConnJdbcSqlServer(DriverManager.getConnection(dbURL));
            System.out.println("Connected to SqlServer");
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public Connection getConnJdbcSqlServer() {
        return connJdbcSqlServer;
    }

    public void setConnJdbcSqlServer(Connection connJdbcSqlServer) {
        this.connJdbcSqlServer = connJdbcSqlServer;
    }

    public void Close(){
        try {
            connJdbcSqlServer.close();
            System.out.println("SqlServer Connection Closed...");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

The problem now comes in when I want to fill the a combobox using the SqlServerConnection (com.microsoft.sqlserver.jdbc.SQLServerDriver) because the JxComboBoxFiller expects a "normal" Connection (java.sql.Connection).
How do I bridge this? I just cant wrap my head around this.
Comment: What the problem you have the Connection connJdbcSqlServer, why not used it ? is there any compile/running time error?
Comment: I get "The constructor ComboBoxFiller(JdbcSQLServerConnection, EnvironmentComboBox, String) is undefined". It suggests a few changes and most of then pertains to changing the JdbcSQLServerConnection to Connection, or it wants to change Connection to JdbcSQLServerConnection.
Answer: get the connection from your JdbcSQLServerConnection by calling getConnJdbcSqlServer and pass the returned object to your ComboBoxFilter
for example:
JdbcSQLServerConnection sqlConnection= new JdbcSQLServerConnection(path);
sqlConnection.Connect();

Connection connection = sqlConnection.getConnJdbcSqlServer();
ComboBoxFiller(connection,...);


C# - Acesso Negado Arquivos Windows

Question: Olá estou a fazer um software capaz de escanear determinados arquivos do Windows, onde nele deixo filtrados certos tipos de extensões, porém, ao colocar para escanear da a seguinte mensagem de acesso negado em determinadas pastas.
O código seria o seguinte:
DirectoryInfo dir_Local = new DirectoryInfo(tb_UnidadeHD.Text);

string[] extensao = new string[] { "*.WsF", "*.lnk", "*.vbs", "*.vbe", "*.js", "*.com" };
string[] dir_Info = Directory.GetFiles(tb_UnidadeHD.Text, extensao.ToString(), SearchOption.AllDirectories); ;

try
{
    foreach (string procura in dir_Info)
    {
        lb_Arquivos.Text = string.Format("Escaneando: {0}", procura);
        string result = ScanForVirus(procura);

        if (!dir_Local.Exists)
            MessageBox.Show(string.Format("Diretório de origem não existe ou não pôde ser encontrado: {0}", dir_Local), "AlegoTools", MessageBoxButtons.OK, MessageBoxIcon.Error);
        else
        {
            if (result != string.Empty)
                listBox_Files.Items.Add(result);
            else
                MessageBox.Show(string.Format("Não foi encontrado nenhum vírus em {0}", dir_Local), "AlegoTools", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
catch { }

Se poderem me dar uma luz, pois tentei outros meios mas sem sucesso, ele simplesmente nao consegue escanear certas partes do windows, mesmo estando como admin, mostra como se estivesse sem acesso pelo programa, e ele estã configurado para executar como administrador
Comment: Colocar um `catch` vazio é a última coisa que deveria fazer. Você não colocou a mensagem. Preciso sair, depois eu vejo se dá pra responder.
Comment: "da a seguinte mensagem de acesso negado em determinadas pastas." você chegou a observar o erro no debug? em minha resposta estou deduzindo que seja a exceção  [UnauthorizedAccessException](https://msdn.microsoft.com/pt-br/library/system.unauthorizedaccessexception(v=vs.110).aspx)
Comment: A questao nao seria o catch vazio, pois, ja utilizei a exceção do UnauthorizedAccessException e o erro seria o mesmo.
Answer: Aparentemente e só um problema de permissão de pasta, você pode tentar verificar as permissões acessando as propriedades na guia segurança você pode verificar permissões da pasta.
Exemplo

Tratando a exceção
Como o usuário não tem acesso o jeito e notificar ele sobre sua permissão e se for o caso permita o acesso para ele a pasta desejada.
Código
catch (UnauthorizedAccessException ex)
{
  MessageBox.Show("No Momento Você Não Tem permissões para realizar esta operação , Contate o Administrador Do Sistema  ! Detalhes : " + ex.Message, "Alerta ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}

Comment: Nesse caso você deve reformular a pergunta afinal seu objetivo e forçar a leitura dos diretórios e não tratar um erro , mas infelizmente neste caso não sei te dizer se isso e possível .
Comment: Não teria como dar permissão, pois o aplicativo é para fazer varredura em varias máquinas, e fica dificil ter que dar permissão maquina por maquina, até são varias pastas que dao o erro de acesso negado, ja cheguei a dar permissao em algumas, mas sao varias que dão tal problema. Queria ver se tinha alguma opção de forçar ele a ler tal pastas.
Comment: Isso, seria forçar a ler os diretórios, porém mesmo o nível de acesso como admin geral ainda não obtém o acesso mesmo ate colocando para ignorar as partes em que obtém o erro de nível de permissão.

C# - Acesso Negado Arquivos Windows


Why is a UIBarButtonItems width 0 when it's the minimum size

Question: I have a UIBarButton in InterfaceBuilder:

But when the width is the minimum size (without hiding any of the button), the width becomes zero:

When you increase the width to anything but the minimum, all is right with the world:

I checked the width programmatically and sure enough, the width is zero when it's the minimum size. When you increase the size by 1 or more, the width is correct. Is this a bug or is this intentional?
Answer: 0 means it takes the calculated minimum size based on the button text, so it isn't a bug, it's a feature. Note that you can't make the button smaller than this minimum size, because the text of a toolbar button item should not change (and the text should always be visible).
Comment: Cool, I wish that they'd remove that "feature". Getting 0 back for  a bar button item that is clearly not 0 width, is not exactly expected behavior. But the reasoning does make sense.


A difficult integral of reciprocal of sum of exponentials

Question: Consider the integral: $$\int_0^\infty \frac{1}{e^{ax}+e^{bx}+e^{cx}} dx$$ where $a, b, c$ are complex numbers.
I encounter such integral when dealing with Laplace transform of co-functions. It turns out that the online integral calculator couldn't even give any result.
I suppose the integrand is well-defined since $e^x$ has no branch point on the whole complex plane.
Maybe the integrand has poles, but I believe the integral exists in the sense of Cauchy p.v..
I am a bit reluctant to use the substitution $y=e^x$ since $y^p$ in general has branch points for complex $p$.
Is there any method to compute such integral?
Any help will be appreciated.
EDIT: since a result in closed form is very unlikely to exist, a series as an answer will also be appreciated.
Comment: You need some restrictions on $a,b,c$, I believe. If they are all nonpositive real numbers, the integral diverges (perhaps this is encapsulated in some formula, though).
Comment: Do you expect a closed form? If it can't be found in general, would some kind of series solution be useful?
Comment: @YuriyS Any help will be appreciated. Indeed, as long as the result is in terms of $a, b, c$ then it is useful enough.
Comment: Even special cases such as $a=b=1$, $c > 0$ don't seem to have a closed form.
Comment: If $a$, $b$ and $c$ are all rationally related (say $a = i d$, $b = j d$, $c = k d$ with $i,j,k$ positive integers and $d > 0$, the transformation $e^{dx} = t$ gives you the integral of a rational function, which can be done using the partial fraction decomposition of that rational function (and thus in terms of residues at the roots).  This makes a nice general solution unlikely.
Comment: @RobertIsrael If a, b, c are linearly related e.g. $a=s+id$ and $b=s+jd$ and $c=s+kd$, then are there any chances?
Comment: @RobertIsrael, there is a closed form for $a=b,c>0$ though, in terms of the hypergeometric function ${_2 F_1}$. Wolfram gives it, and I think it's not that hard to derive, from the integral $$\int_0^1 \frac{dt}{2 t^{1-a}+t^{1-c}}$$
Comment: @YuriyS As you mentioned hypergeometric functions, would you like to look at my question, which nobody answered yet? https://math.stackexchange.com/q/2651292/512032
Answer: I think this integral deserves to be studied more. Let's introduce a function of three variables:
$$f(a,b,c)=\int_0^\infty \frac{1}{e^{ax}+e^{bx}+e^{cx}} dx$$
The function is obviously symmetric in all the variables.
While the integral doesn't have a closed form, what's important is: how else can we define the function and determine its properties or connect it to something else.
First, let's consider partial derivatives:
$$\frac{ \partial f}{ \partial a} =-\int_0^\infty \frac{xe^{ax}}{(e^{ax}+e^{bx}+e^{cx})^2} dx$$
Same with the other two variables.
On the other hand, we have:
$$\frac{d}{dx} \frac{1}{e^{ax}+e^{bx}+e^{cx}}=-\frac{ae^{ax}+be^{bx}+ce^{cx}}{(e^{ax}+e^{bx}+e^{cx})^2}$$
Thus, using integration by parts:
$$a\frac{ \partial f}{ \partial a}+b\frac{ \partial f}{ \partial b}+c\frac{ \partial f}{ \partial c}=- \int_0^\infty \frac{x(ae^{ax}+be^{bx}+ce^{cx})}{(e^{ax}+e^{bx}+e^{cx})^2} dx=$$
$$=\frac{x}{e^{ax}+e^{bx}+e^{cx}} \bigg|_0^\infty-\int_0^\infty \frac{1}{e^{ax}+e^{bx}+e^{cx}}dx=-f$$
So our function obeys a first order linear PDE:

$$a\frac{ \partial f}{ \partial a}+b\frac{ \partial f}{ \partial b}+c\frac{ \partial f}{ \partial c}+f=0$$

The form of this equation obviously generalizes to any number of exponentials in the denominator.

Of course, this PDE doesn't tell us much more than the integral itself. Moreover, it has infinitely more solutions than just this integral.
But maybe it might be useful in some context.
As for boundary conditions, we can look back at the integral and see that
$$\lim_{a \to +\infty} f(a,b,c)=0$$
For $a>0$ we also have:
$$\lim_{b,c \to -\infty} f(a,b,c)=\frac{1}{a}$$
To this we can add (again for $a>0$):
$$f(a,0,0)=\frac{\ln 3}{2 a}$$
Same for the other variables. The above should be more than enough as far as boundary conditions go.
If we try to solve the PDE by separation of variables we have:
$$f(a,b,c)=A(\lambda,\mu) a^{\lambda} b^{ \mu-\lambda} c^{-1-\mu}$$
For some arbitrary constants $\lambda, \mu, A(\lambda,\mu)$. Since the equation is linear we can sum any number of solutions with different parameters and different amplitudes. Not sure if we can satisfy all the initial conditions that way though, I'll have to look into this further. The general solution (assuming the separation of variables of course, there are other kinds of solutions) could look like:
$$f(a,b,c)=\int_{-\infty}^\infty \int_{-\infty}^\infty A(\lambda,\mu) a^{\lambda} b^{ \mu-\lambda} c^{-1-\mu} d \lambda d \mu$$
Where of course $A(\lambda,\mu)$ could be made zero for any range to keep the solution finite.

Now, the integral also allows us to derive a number of simple functional equations, by changing the variable. For example:
$$f(a,b,c)=\frac{1}{a} f \left(1,\frac{b}{a},\frac{c}{a}  \right)$$
As well as a more symmetric one:
$$f(a,b,c)=\frac{1}{abc} f \left(\frac{1}{ab},\frac{1}{bc},\frac{1}{ca}  \right)$$
In general:
$$f(\alpha a,\alpha b,\alpha c)=\frac{1}{\alpha} f \left(a,b,c  \right)$$

Additionally, if we change the variable $$e^{-x}=t$$ we obtain: $$f(a,b,c)=\int_0^1 \frac{dt}{t^{1-a}+t^{1-b}+t^{1-c}}$$
As Robert Israel points our in the comments, if the parameters are rational multiplies of each other, we can usually transform this to an integral of a rational function, which always has a closed form.

All in all, I would consider this integral to be as interesting as Carlson elliptic integrals, as it too can be interpreted as the generalized several numbers mean. Might be worth looking into its properties more.
The fact that it's related to means can be trivially seen. Really, let $0<a \leq b \leq c$:
$$\frac{1}{3c}= f(c,c,c) \leq f(a,b,c) \leq f(a,a,a)= \frac{1}{3a}$$
$$a \leq \frac{1}{3 f(a,b,c)} \leq c$$
Then there exists a number $a \leq \mu \leq c$ such that:
$$f(a,b,c)=f( \mu, \mu, \mu) = \frac{1}{3 \mu}$$
As $ \mu$ represents a generalized mean of $a,b,c$, there may be some iterative algorithm which converges to it (just like arithmetic-geometric mean and Carlson three number algorithm for his integrals).
The above arguments work for any function of the form:
$$f_n(a_1,a_2,\dots,a_n)=\int_0^\infty \frac{dx}{e^{a_1x}+e^{a_2 x}+ \cdots + e^{a_n x}}$$
Comment: @Szeto, see my last edit at the bottom of the post. You might be interested in the fact that this integral is related to generalized means
Comment: I am delighted to see the elaboration on your answer, but I think I need some more time to fully understand your ideas. Also, thanks for giving me new directions!
Comment: @Szeto, you are welcome, feel free to as any questions. In general, the family of integrals $$f_n(a_1,a_2,\dots,a_n)=\int_0^\infty \frac{dx}{e^{a_1x}+e^{a_2 x}+ \cdots + e^{a_n x}}$$ is an interesting kind of symmetric functions to study
Comment: Fantastic idea! My question is, why did you solve it using separation of variables? Shouldn't one use substituion techniques instead, transforming it into a different, but more easily solvable equation?
Comment: @user458276, I didn't solve it, as I doubt the separation of variables gives the original integral, i.e. they are two different kinds of solutions. And I don't see any way to simplify this equation. If you do, you could post it here though
Comment: @YuriyS Your answer is so rich in content that you totally astonished me. If there is a fast algorithm to find $\mu$ when $a, b, c$ are given, then this integral is actually so simple. You deserve the green tick.
Comment: @Szeto, thank you, but I must warn you that this algorithm may be extremely difficult to find. Maybe impossible
Answer: Here's a very sloppily derived series representation. I just went through the algebra without looking out for convergence and divergence problems, so I have no idea how useful this will be (in fact, it appears that the final result hardly ever converges).
$$\begin{align}
\int_0^\infty \frac{dx}{e^{ax}+e^{bx}+e^{cx}}
&= \int_0^\infty \frac{e^{-cx}}{e^{(a-c)x}+e^{(b-c)x}+1}dx\\
&= \int_0^\infty \frac{e^{-cx}}{1-(-e^{(a-c)x}-e^{(b-c)x})}dx\\
&= \int_0^\infty e^{-cx}\sum_{n=0}^\infty (-1)^n(e^{(a-c)x}+e^{(b-c)x})^n dx\\
&= \sum_{n=0}^\infty (-1)^n\int_0^\infty e^{-cx}(e^{(a-c)x}+e^{(b-c)x})^n dx\\
&= \sum_{n=0}^\infty (-1)^n\int_0^\infty e^{-cx}\sum_{k=0}^n\binom{n}{k}e^{(a-c)xk}e^{(b-c)x(n-k)} dx\\
&= \sum_{n=0}^\infty (-1)^n \sum_{k=0}^n\binom{n}{k}\int_0^\infty e^{-cx}e^{(a-c)xk}e^{(b-c)x(n-k)} dx\\
&= \sum_{n=0}^\infty (-1)^n \sum_{k=0}^n\binom{n}{k}\int_0^\infty e^{(a-c)xk+(b-c)x(n-k)-cx} dx\\
&= \sum_{n=0}^\infty (-1)^n \sum_{k=0}^n\binom{n}{k}\int_0^\infty e^{((a-c)k+(b-c)(n-k)-c)x} dx\\
&= \sum_{n=0}^\infty (-1)^n \sum_{k=0}^n\binom{n}{k}\int_0^\infty e^{(ak+bn-bk-cn-c)x} dx\\
&= \sum_{n=0}^\infty (-1)^n \sum_{k=0}^n\binom{n}{k} \bigg[ \frac{e^{(ak+bn-bk-cn-c)x}}{ak+bn-bk-cn-c} \bigg]_{0}^{\infty} \\
&= \sum_{n=0}^\infty (-1)^n \sum_{k=0}^n\binom{n}{k}\frac{1}{ak+bn-bk-cn-c}  \\
&= \sum_{n=0}^\infty (-1)^n \sum_{k=0}^n\binom{n}{k}\frac{1}{(a-b)k+(b-c)n-c}  \\
\end{align}$$
Comment: Maybe that simply implies that Laplace transform of co-functions rarely exists. Thanks for your help!
Comment: I think one problem is that the first series expansion is valid when $|e^{(a-c) x} + e^{(b-c) x}| < 1$, but that's false when $x$ is near $0$.


RV042 - switch needed

Question: I have a Cisco RV042 4-port but unfortunately I ran out of ports and I need to connect 2 more servers to it. I'm planning to get a SOHO switch, but I would like some recommendations before getting one. I was thinking a Dell PowerConnect.
Any ideas will be appreciate it.
Answer: It depends on whether you are looking for a managed or unmanaged switch. Dell PowerConnect offers plenty of features at a reasonable price, but you have to pay extra for a longer warranty. Personally, I tend to be biased towards HP ProCurve they have solutions for every size and budget, but what wins me over is that their products come with a life time warranty. Performance has never been an issue either.
(They stand by their warranty)
You can check prices at Newegg, I imagine you are looking for an 8 port switch.
Comment: ProCurve FTW!!!
Answer: Assuming that you need a managed switch, decide whether you need fully-managed (SNMP) or web-managed, and get an 8-port gigabit switch. Move all of the servers to it, with a single connection to a 100Mbit port on the RV042.
I have no particular input on which brands/models to go with - I'd actually recommend checking reviews at Newegg and possibly (less technical) Amazon.
Answer: You can probably get by with a cheap 8-port Gigabit switch, any of the ones from D-Link, Linksys or Netgear should be fine and cheap.
If you do want/need managed features then look at the "layer 2" maanged versions from any of those vendors, still fairly cheap.
The ProCurve, Cisco, Juniper, 3com etc. managed switches are almost certainly far more then you need (and will cost far more then you can afford as well).

RV042 - switch needed


SQL count distinct over partition by cumulatively

Question: I am using AWS Athena (Presto based) and I have this table named base:

id
category
year
month

1
a
2021
6

1
b
2022
8

1
a
2022
11

2
a
2022
1

2
a
2022
4

2
b
2022
6

I would like to craft a query that counts the distinct values of the categories per id, cumulatively per month and year, but retaining the original columns:

id
category
year
month
sumC

1
a
2021
6
1

1
b
2022
8
2

1
a
2022
11
2

2
a
2022
1
1

2
a
2022
4
1

2
b
2022
6
2

I've tried doing the following query with no success:
SELECT id,
       category,
       year,
       month,
       COUNT(category) OVER (PARTITION BY id, ORDER BY year, month) AS sumC FROM base;

This results in 1, 2, 3, 1, 2, 3 which is not what I'm looking for. I'd rather need something like a COUNT(DISTINCT) inside a window function, though it's not supported as a construct.
I also tried the DENSE_RANK trick:
  DENSE_RANK() OVER (PARTITION BY id ORDER BY category)
+ DENSE_RANK() OVER (PARTITION BY id ORDER BY category)
- 1 as sumC

Though, because there is no ordering between year and month, it just results in 2, 2, 2, 2, 2, 2.
Any help is appreciated!
Comment: can you share a bigger sample from your data, with the updated expected ranking?
Comment: @lemon just edited with a second id
Comment: I did not understand the logic behind sumC column. Can you explain a bit more?
Comment: @shantanuo id=1 has 1 distinct category as of 2021/06 (therefore sumC is 1), then has 2 distinct categories as of 2022/08 (therefore sumC is 2), and still has 2 distinct categories as of 2022/11 (therefore sumC is still 2). what i wanted was a cumulative sum of distinct categories per id over time
Comment: You have mentioned 2 distinct categories as of 2022/08, but I see only 1 row for 2022/08
Comment: @shantanuo the 2nd distinct category is accumulated from the previous rows (2021/06), i need to count and keep track of all distinct categories as of the recent date year/month column
Comment: So if you have a table like this... http://sqlfiddle.com/#!9/3e7f3d/1 You need output like this http://sqlfiddle.com/#!9/5436b2/1 ?
Comment: @shantanuo yes that's exactly right
Answer: One option is

creating a new column that will contain when each "category" is seen for the first time (partitioning on "id", "category" and ordering on "year", "month")
computing a running sum over this column, with the same partition

WITH cte AS (
    SELECT *,
           CASE WHEN ROW_NUMBER() OVER(
                         PARTITION BY id, category
                         ORDER     BY year, month) = 1
                THEN 1
                ELSE 0
           END AS rn1
    FROM base
    ORDER BY id,
             year_,
             month_
)
SELECT id,
       category,
       year_,
       month_,
       SUM(rn1) OVER(
            PARTITION BY id
            ORDER     BY year, month
       ) AS sumC
FROM cte


how to stretch selected menu item to the left edge of the window?

Question: I have a block with several items. When I click on the menu item it is highlighting and extending to the left border of the window.
I did this with the help of an absolutely positioned element, and set the width to 1000px, but this option does not work. This red bar should rest against the edge of the window at any resolution.

html

item 1

item 2

item 3

item1content

item1content

item1content

item1content

item1content

css
.flex-menu-area {
    background: #fff;
    width: 100%;
    height: 512px;
    .flex-menu {
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        height: 100%;
        .left-flex-column {
            max-width: 256px;
            width: 100%;
            outline: 1px solid gray;
            height: 512px;
            .flex-menu-select {
                font-size: 20px;
                line-height: 26px;
                font-weight: 600;
                text-align: left;
                color: $text-color;
                padding-top: 43px;
                padding-bottom: 43px;
                max-width: 100%;
                border-bottom: 1px solid gray;
                position: relative;
                &:hover {
                    background: #ccc;
                    &:before {
                        position: absolute;
                        width: 1000px;
                        height: 100%;
                        content: "";
                        display: block;
                        top: 0px;
                        left: -1000px;
                        background: red;
                    }
                }

            }
        }
        .right-left-column {
            outline: 1px solid gray;
            height: 512px;
            width: 884px;
            background: #fff;
            display: -webkit-flex;
            display: -moz-flex;
            display: -ms-flex;
            display: -o-flex;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
            background: #eee;
            .object {
                outline: 1px solid red;
                font-size: 20px;
                line-height: 40px;
            }
        }
    }
}

Solution:
&:before {
    position: absolute;
    width: 100vw;
    right: 0;
    height: 100%;
    content: "";
    display: block;
    top: 0px;
    background: #fff;
    z-index: -1;
}

Comment: instead of `1000px` set it to `100%` ?
Comment: This will not work correctly. 100% will be from the width of flex-menu-select.
Comment: can you build a JS fiddle by any chance ?
Answer: Set the width and left values of your &:before to:
width: calc((100vw - 100%) /2);
left: calc(0 - ((100vw - 100%) /2));

I think that should help, but I don't have access to a screen large enough to test right now so apologies if my calcs are slightly off.
Comment: Working solution:

&:before {
 position: absolute;
 width: 100vw;
 right: 0;
 height: 100%;
 content: "";
 display: block;
 top: 0px;
 background: #fff;
 z-index: -1;
}