Exclude a JavaScript file from a node

Question: I'd like to exclude a js file from loading on to a specific node.
Right now my libraries.yml file looks like this:
global-styling:
  version: 1.x
  css:
    theme:
      css/bootstrap/bootstrap.css: {}
      css/style2.css: {}
      css/header.css: {}
      css/color-1.css: {}
      css/themify-icons.css: {}
      css/jquery-ui.css: {}
  js:
    js/bootstrap.js: {}
    js/jquery-ui.js: {}
    js/popper.js: {}
    js/tooltip.js: {}
    js/wow.min.js: {}
    plugin/appear/jquery.appear.js: {}
    js/custom.js: {}
  dependencies:
    - core/jquery

I'd like to exclude the js/custom.js from loading on node/4. Alternatively I would like to load that file ONLY for the front page.
Answer: Delete/Exclude js/custom.js from the global-styling section in THEMENAME.libraries.yml and define it as a library at the end of the same file
# THEMENAME.libraries.yml
custom-js:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery

And then include the library conditionally to where you want it using THEMENAME_preprocess_page function in THEMENAME.theme
//THEMENAME.theme
function THEMENAME_preprocess_page(&$variables) {

    //include it if its front_page
    if ($variables['is_front'] == TRUE) {
        $variables['#attached']['library'][] = 'THEMENAME/custom-js';
    }

    //include it if its NOT node 4
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface && $node->id() != 4) {
        $variables['#attached']['library'][] = 'THEMENAME/custom-js';
    }
}

For more info read the docs
Answer: If you want to load the file only for the front page, separate that file to another library like:
global-custom-styling:
  js:
    js/custom.js: {}

And preprocess page then attach library:
function mytheme_preprocess_page(&$variables){
  if ($variables['is_front'] == TRUE) {
    $variables['#attached']['library'][] = 'my-theme/global-custom-styling';
  }
}

Exclude a JavaScript file from a node


How to check the charset of string in Java?

Question: In my application I'm getting the user info from LDAP and sometimes the full username comes in a wrong charset. For example:
ТеÑÑ61 ТеÑÑовиÑ61

It can also be in English or in Russian and displayed correctly. If the username changes it's updated in database. Even if I change the value in the db it wont solve the problem.
I can fix it before saving by doing this
new String(incorrect.getBytes("ISO-8859-1"), "UTF-8");

However, if I will use it for the string including characters in Russian (for ex., "Тест61 Тестович61") I get something like this "????61 ????????61".
Can you please suggest something that can determine the charset of string?
Comment: Oh no, I have never noticed it, but I've been voting up for answers though. Now I will know, thank you for pointing it out for me.
Answer: Strings in java, AFAIK, do not retain their original encoding - they are always stored internally in some Unicode form.
You want to detect the charset of the original stream/bytes - this is why I think your String.toBytes() call is too late.
Ideally if you could get the input stream you are reading from, you can run it through something like this: http://code.google.com/p/juniversalchardet/
There are plenty of other charset detectors out there as well
Comment: Thanks a lot for help! I'm not sure if I can get the input stream cas the user data is taken from context using UserService. Other way is probably to fix values in LDAP.
Comment: the link is dead
Answer: I had the same problem. Tika is too large and juniversalchardet do not detect ISO-8859-1. So, I did myself and now is working well in production:
public String convert(String value, String fromEncoding, String toEncoding) {
  return new String(value.getBytes(fromEncoding), toEncoding);
}

public String charset(String value, String charsets[]) {
  String probe = StandardCharsets.UTF_8.name();
  for(String c : charsets) {
    Charset charset = Charset.forName(c);
    if(charset != null) {
      if(value.equals(convert(convert(value, charset.name(), probe), probe, charset.name()))) {
        return c;
      }
    }
  }
  return StandardCharsets.UTF_8.name();
}

Full description here: Detect the charset in Java strings.
Comment: Have you tried this with a large `String` and a large number of charsets in the `for` loop? Is it fast enough?
Comment: Hi @Thomas, I haven't tried. My case was detecting UFT-8 from ISO-8859-1, mainly because of third part JavaScript libraries. Just thought of adding some more code, hoping it will be more useful.
Answer: I recommend Apache.tika CharsetDetector
CharsetDetector detector = new CharsetDetector();
detector.setText(yourStr.getBytes());
detector.detect();  // <- return the result, you can check by .getName() method

Further, you can convert any encoded string to your desired one, take utf-8 as example:
detector.getString(yourStr.getBytes(), "utf-8");

Comment: This library adds 45 Mb to the final binary!
Comment: Based on the javadoc for String.getBytes() here:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#getBytes(), it seems that performing yourStr.getBytes() would return the byte equivalent of string encoded in Default Charset. Therefore, detector.detect() will always return the Default Charset as the Charset of yourStr. I don't see how this can ever work correctly.
Answer: I highly appreciate Lluís Turró Cutiller's answer (+1), but want to add a variant based on that.
private String convert(String value, Charset fromEncoding, Charset toEncoding) throws UnsupportedEncodingException {
    return new String(value.getBytes(fromEncoding), toEncoding);
}

private boolean probe(String value, Charset charset) throws UnsupportedEncodingException {
    Charset probe = StandardCharsets.UTF_8;
    return value.equals(convert(convert(value, charset, probe), probe, charset));
}

public String convert(String value, Charset charsetWanted, List<Charset> charsetsOther) throws UnsupportedEncodingException {
    if (probe(value, charsetWanted)) {
        return value;
    }
    for (Charset other: charsetsOther) {
        if (probe(value, other)) {
            return convert(value, other, charsetWanted);
        }
    }
    System.err.println("WARNING: Could not convert string: " + value);
    return value;
}

Answer: Your LDAP database is set up incorrectly.  The application putting data into it should convert to a known character set encoding, in your case, likely UTF_16.  Pick a standard.  All methods of detecting encoding are guesses.
The application writing the value is the only one that knows definitively which encoding it is using and can properly convert to another encoding such as UTF_16.
Answer: In your web-application, you may declare an encoding-filter that makes sure you receive data in the right encoding.
<filter>
    <description>Explicitly set the encoding of the page to UTF-8</description>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

A spring provided filter makes sure that the controllers/servlets receive parameters in UTF-8.
Comment: This only applies to a spring application. Also, forcing the encoding may not work if basic authentication is being used.


Drupal Less cache keeps generating cache file that does allow access to the apache server

Question: How do I ensure that auto-generated css cache files (related to the Less module) are being generated with the permissions necessary for the server to access.
Currently, whenever I clear all caches (with drush cc all), I lose all of my site's css styles and get the following error:

LESS could not create a directory in sites/default/files/less/52741f7e343834.56376384/sites/all/themes/my_custom_theme/css

When I go to look at the permissions (ls -l) for the files in sites/default/files/less, the directory 52741f7e343834.56376384 (which I assume is the new cache file the server is trying to create the other stuff in) it has the wrong ownership <correct-user>:<correct-user>, rather than <correct-user>:apache (it's centos, so that's the apache server group). All the other cache directories have the correct owner permissions.
So how do I ensure that the system is creating these cache files properly such that I don't have to set the file ownership every time I clear the cache to get my styles back?
This is a new problem for my site and I suspect it is because I updated the Less module for Drupal 6 and added the lessphp library to my site (though perhaps I am mistaken).
Answer: I do three things.

I put myself in the apache group.
Set my umask and the httpd process to 0022
chmod sites/default/files to 2775

The first step lets me write to the directory. The second step makes sure that files I create have group write permission, and that apache does the same.  The third step tells the OS to always use the group of the directory owner.
You should then be able to drush cc all and have Apache create the LESS files.
For your initial fix, you may have to fix up the perms recursively. Eg,
chown -R apache.apache docroot/sites/default/files/
find docroot/sites/default/files/ -type d -exec chmod 2775 {} \;
find docroot/sites/default/files/ -type f -exec chmod 664 {} \;

I would also suggest reading Securing file permissions and ownership.  The comments have a good duscussion about the setgid bit and potential downfalls.
Comment: thanks, worked like a charm. and i appreciate the explanations.


Migrate paragraph fields

Question: I have migrated Drupal 7 website to Drupal 8 version using the core migrate_drupal_ui module successfully but the paragraph module was broken upgrade path which results in final that the paragraph bundles not migrated and I have created in the new site like the old.
Now I need to migrate content for the paragraph fields only and update the nodes, I did some research and found possible solutions as follows:
1- Custom migrate plugin But I don't know how to edit existing.
2- custom script to read the nodes from other site by creating feeds and update.
<code>//$nid get from feeds.
$entity = entity_load('node', $nid);

$entity->set('field_audit',
['field_number' => [0 => ['value' => 4]],
'field_regular_materials' => [0 => ['value' => '44']],
'field_verification' => [0 => ['value' => '444']]], FALSE);

$entity->save();
</code>

That code gives error Fatal error: Maximum function nesting level of '256' reached, aborting!

what is the best practice to achieve.
Comment: This nesting error seems like a php settings issue which is related to the XDebug PHP extension. Have you tried this in your php.ini file? xdebug.max_nesting_level = 512
Answer: I would approach this differently. Using PHPMyAdmin or a Database viewer program, I would look at the Database for the paragraph fields table. Then just export table from D7 as a CSV file.
In D8, fill out 1 node paragraph values, just so you get the table structure, and export table as CSV.
Then with excel (or Libre office Calc) copy and paste values from one CSV to another.
Import CSV to D8 Database.
Clear the cache to see changes.
Comment: Schema differs form 7 to 8 in paragraph module, I need a solution inside drupal itself
Comment: @Mhmdgomma figure out the differences and move the values to the appropriate columns.
Comment: That solution has come to my mind, But I am looking for a generic solution to be reused in other projects

Migrate paragraph fields


Android - List not binding to RecyclerView MvvmCross

Question: I am fairly new to android and I am trying to bind a List I have in my ViewModel to a RecyclerView in my UI. I am using Xamarin and MvvmCross. I have the RecyclerView setup like this:
<android.support.design.widget.NavigationView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:theme="@style/Theme.AppCompat.Light">

<MvvmCross.Droid.Support.V7.RecyclerView.MvxRecyclerView
    android:id="@+id/navigation_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    app:MvxItemTemplate="@layout/menu_item"
    app:MvxBind="ItemsSource MyItems"/>

</LinearLayout>

Here's my menu item:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="48dp" >

   <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="13sp"
        app:MvxBind="Text Title" />

</LinearLayout>

and lastly, my VM List is something like this:
 MyItems = new List<NavItem>
 {
       new NavItem { Title = "Option1" }
       new NavItem { Title = "Option2" }
 };

EDIT:
Here where I set the properties:
List<NavItem> _myItems;
    public List<NavItem> MyItems
    {
        get => _myItems;
        set => SetProperty(ref _myItems, value);
    }

and MyItem:
public string Title { get; set; }

I'm pretty sure it's setup properly; however, for some reason, it won't populate my recycler view. Did I miss something? any help would be very much appreciated. Thanks!
Comment: Change List to MvxObservableCollection and check
Comment: Tried it, still empty
Comment: paste your full Vm once
Comment: if it helps, I am getting this warning: MvxBind:Warning:  4.29 Unable to bind: source property source not found Property:Title on MainViewModel
Comment: Show me the setters of MyItems, and NavItem change as well.,

Public MvxObservableCollection MyItem {get {return MyItem} set {MyItem = value; RaisePropertyChange(() => MyItem}};

Public Class NavItem {
Public string Title {get;Set;}
}
see if the syntex matches
Comment: Updated the post to add those items
Comment: I will use the same code an update the solution soon.
Comment: Great! I'll keep an eye out
Comment: Can you share with us a bit more of your code? How are you navigating to the VM which contains the list? What kind of UI representation does the VM have?
Answer: Figured it out! I had xmlns:app="https: instead of xmlns:app="http:


Jenkins on Docker - Free Swap Space 0

Question: I've noticed that my master node on Jenkins shows
free swap space: 0 B

So I added a swap file as described here.
But this has no effect. What am I doing wrong?
Comment: @olyv my container was running in a kubernetes cluster. After giving the deployment more resources, the problem was solved. Good luck and have a great day!
Comment: Thanks for your response. I will continue investigate issue wtih my jenkins
Comment: Hi @dknaack, any luck oh finding the reason for this?
Answer: Run the following command to see if your host has a swap file configured:
free|grep -i Swap
Swap:            0          0          0

If you get "Swap:            0          0          0" like you see above your host has no swap configured.
Configure a swap file on your host:
sudo dd if=/dev/zero of=swapfile bs=1M count=1K
sudo mkswap swapfile
sudo chown root:root swapfile
sudo chmod 600 swapfile
sudo swapon swapfile

Verify your swap is configured:
free|grep -i Swap
Swap:      1048572          0    1048572

Good, we have a swap on the host.
Run your Jenkins docker by typing:
docker run --privileged -p 8080:8080 --name jenkins -p 50000:50000 jenkins

Notice you must run the docker in privileged mode.
When you run your Jenkins docker in privileged mode the host's swap will be available inside the docker, so your Jenkins master will have a working swap.
If your host already has a working swap in place, all you will need to do is run the Jenkins docker in privileged mode.

Jenkins on Docker - Free Swap Space 0


em.createNativeQuery executa primeiro do que o em.persist e agora?

Question: Estou desenvolvendo uma aplicação com Hibernate + Spring mv. o spring cuida da dependência do EntityManager para meu DAO, porem tenho o seguinte problema.

eu persisto um objeto chamado User
depois eu executo createNativeQuery com "insert into tabela1 (campo1, campo2) select campo1, campo2 from User"

com isso notei que na tabela1 não estava registrando o User, fui conferir habilitando show_sql e no console o hibernate executa primeiro o createNativeQuery depois o persist, independente da ordem que os dois foram escritos.
Existe alguma forma de configurar o hibernate pra que ele mantenha a ordem?
Comment: Poderia colocar o código na pergunta para olharmos? :) Inclua também a saída do show_sql
Answer: O problema é causado porque muitas das operações comuns são armazenadas em uma espécie de fila em memória, que geralmente é descarregada no banco de uma só vez ao fechar o EntityManager. O Hibernate tenta assim otimizar o acesso ao banco de dados. Porém, queries nativas não passam por essa fila e para o SGBD é como se o primeiro comando nunca tivesse ocorrido.
O ideal nesse caso é executar o método flush() após o persist() para forçar que os comandos aguardando na fila foram enviados ao banco de dados, neste caso a inserção.
Comment: Nice! Isso mesmo, Muito obrigado =)


Write the complex number on the polar form $r(\cos\theta + i \sin\theta)=re^{i\theta}$

Question: As it is said in the title.
The number is $4-4i$
I did this
$4-4i=\sqrt 2\,(1+i)=\cos(\pi/4)+i \sin(\pi/4)=\sqrt{2}e^{i(\pi/4)}$
$|4-4i|=\sqrt{2}$, $arg(4-4i)=(\pi/4)+2\pi$
but it's wrong
Comment: In the FAQ section there are directions for writing mathematics with LaTeX in this site.
Answer: At first we calculate the $r$, as $4^2 +4^2 = 32$ $r$ will be $\sqrt{32}$.
Because
$$4-4i=4(1-i)=r \cdot \exp(i \varphi)$$
 when making a sketch we see that the angle is $$\frac{7\pi}{4}$$ so the whole number will be
$$4-4i= \sqrt{32} \cdot \exp\left(i \cdot \frac{7\pi}{4}\right)$$
Answer: $$4+4i=4(1-i)=4\sqrt 2\left(\cos\frac{\pi}{4}-i\sin\frac{\pi}{4}\right)=4\sqrt 2e^{-i\pi/4}$$
And, of course, you should add multiples of $\,2\pi\,$ to the argument, unless you want one single value.
Answer: Let  $4-4i=r(\cos\theta+i\sin\theta)$ where $r\ge 0$
Equating the real & the imaginary parts
$4=r\cos\theta, -4=r\sin\theta$
Squaring and adding we get $r^2=4^2+4^2=32\implies r=4\sqrt2$
$\implies \cos\theta=\frac1{\sqrt2}>0, \sin\theta=-\frac1{\sqrt2}<0 $
From the definition of $\arctan\frac yx,\theta= \arctan\frac{(-1)}1=\arctan(-1)=-\frac{\pi}4$  as the principal value of arctan lies $\in\left[-\frac\pi2, \frac\pi2\right]$


Integrating the errorfunction using the method of undetermined coefficients

Question: $\DeclareMathOperator\erf{Erf}$
I am trying to solve using the method of undetermined coefficients:
$$\int\erf(x)dx$$
With the method of undetermined coefficients one would start by "simply" guessing a general solution to the integral.
In the case of $\int\erf(x)dx$ my calculusbook suggests we try:
$$\int\erf(x)=P(x)\erf(x)+Q(x)e^{-x^2}+C$$
Here P and Q are polynomials to be determined.
Question: Where on earth does this guess come from? I don't intuit it at all. Any help would be appreciated.
Comment: It's called guessing for a reason ... :)
Comment: @HagenvonEitzen I think it's supposed to be an educated guess... but for now the "educated" part is beyond me...
Answer: What could be on the right hand side of
$$\int f(x)\,\mathrm dx = \ldots? $$
After differentiating, the left hand side becomes $f(x)$, of course. So we want something that produces - initially perhaps with some additional "waste" - $f(x)$. By the product rule, $xf(x)$ does produce $f(x)$ (and also $xf'(x)$, with which we have to deal as well), so allowing $xf(x)$ would be a good idea. A slight generalization is to allow not just $x$ times $f(x)$, but in fact $P(x)f(x)$ for arbitrary polynomial $P$, as well as $Q(x)f'(x)$ in order to somehow hopefully cancel the "waste". We may want to continue with polynomial multiples of $f''(x)$ etc., but fortunately in our specific example, $f''$ is already a polynomial multiple of $f'$ ...


Dense-in-itself open sets in a subspace of the real line

Question: Given an uncountable set $X\subset [0,1]$ it is easy to write $X$ as a disjoint union of a perfect set $P$ (perfect in the subspace $X$) and an at most countable set $C$: just take $P$ as the set of condensation points of $X$ and $C$ as its complement in $X$. (we consider $X$ equipped with the subspace topology.)
I want to find an open set in $X$ which is dense-in-itself.
Is this possible? An open set of a dense-in-itself/perfect space is itself dense-in-itself, but from this point onwards I am most unsure how to proceed correctly.
Any comments will be appreciated. Thank you for your help.
Comment: The statement in the first line is false. For instance, a Bernstein set has the cardinality of the continuum, but it contains no perfect set.
Comment: I have expressed myself without enough clarity (thus the edit). I meant a perfect set, when considered in the subspace topology.
Answer: It seems the following.

I want to find an open set in $X$ which is dense-in-itself. Is this possible?

It is not always possible. Let $\{a_n\}$ be an enumeration of all rational points of the unit segment $[0,1]$. Let $$X=\{(1/n, a_n):n\in\Bbb N\}\cup (\{0\}\times ([0,1]\setminus\Bbb Q)) \subset\Bbb R^2.$$ Then $X$ is an uncountable zero-dimensional metric space with a dense set of  isolated points. But $X$ belongs to $\Bbb R^2$, not to $\Bbb R$. To solve this little problem we recall that each zero-dimensional second countable space can be embedded into Cantor set, which can be embedded into the unit segment.

(cited from "General Topology" by Ryszard Engelking. )
Comment: Nice example. Thank you.
Comment: As your answer is written, $X=\emptyset$ - I'm not sure what you meant.
Comment: @user241898 Thanks. Corrected.
Answer: This is an easier version of Alex Ravsky's idea.
Let $C$ be the usual middle-thirds Cantor set, let $D$ be the set of midpoints of the open intervals deleted in the construction of $C$, and let $X=C\cup D$; then $D$ is a dense set of isolated points in $X$, so $X$ has no dense-in-itself open subset.
Comment: This is a very simple counterexample - thank you.
Comment: @André: You're welcome.


Search some contents and update it in Eclipse search view

Question: I have created Eclipse plugin to search some contents and update it in eclipse search view, but I am unable to do so since createControl() of ISearchResultPage is called only once in its life cycle.
I need to call it every time my search result changes so that I can erase all the previous widgets and update my search result using new widgets accordingly.
Answer: The createContents method is only ever called once. What you can do in your result page is use an IQueryListener to listen for changes to queries.
Add the listener in the createContents method with:
NewSearchUI.addQueryListener(queryListener);

You should remove the listener in the page dispose method:
NewSearchUI.removeQueryListener(queryListener);

Note that the org.eclipse.search.ui.text.AbstractTextSearchViewPage does this for you, you may be able to extend that page rather than write your own complete ISearchResultPage page.
Comment: I had managed that in a different way earlier by hiding and opening the search view every time the search result changes. I will now try with the way you have said.. However I am now facing a new problem. i.e,  I am unable to get the NUMBER of matches found to show in the search view although search result(matches) exist and displayed in the search view. I am getting the NUMBER of matches found in the previous search but not that of the current search. I tried with match event but still same problem exists.. Please help me.
Comment: the way you said is working.. thanks for that but the above problem still exists.. I am not getting number of matches when I display the result on the view


Which is the highest version of Solr that is compatible with the "Apache Solr Search" module?

Question: I have a setup of Drupal 7 with the Apache Solr Search module. I am planning to upgrade the solr server's current installed version(3.6) to a higher version.
The latest version of Solr available in their site is 8.5.1.
Which is the highest version of Solr that is compatible with the module?
Answer: Given there is an issue in the project issue queue (Solr 7 integration) about allowing to use the module with Solr 7, the module is at the moment only compatible with Solr 5 and eventually Solr 6.
Notice that the README.txt file has not been updated since 6 years ago and that the solr-conf directory contains configuration files for Solr 1.4, 3.x, 4.x, and 5.x. This means the module has been tested with Solr 5.x, at least the 5.x version that was available 4 years ago.


Is it ok to hit skipped notes while strumming up?

Question: When I strum up on chords like Dm I keep hitting the strings that aren't suppose to be played. In the last few days I've practiced and am getting better at not hitting them, but I was just wondering does it mater. I just started learning guitar and don't use a pick.
Answer: You can answer this question yourself, by listening to the sounds you are making.
What sound does it make when you hit the strings "that aren't supposed to be played"? Is it a sound you like? Do you want your audience to hear it?
Making music isn't just a matter of making the mechanical movements written on a transcription. It's very important to listen, and adjust to make the sound you want to hear.
Answer: Yes, it absolutely matters.  The other notes are not played because they're not part of the chord.  If you play them, you're no longer playing a Dm, and it will sound incorrect — and potentially horrible.  A C Major chord where you hit the low E isn't the worst, since E is part of the chord, but a Dm featuring the low E would be quite awful.
If you're just strumming chords, you should probably start learning with a pick as well.  It can make things much easier and cleaner.  Strumming with your nails will be quite tough on them and require more control.  (And if you don't have nails, chances are you will be very inaccurate and the tone will be poor.)
Answer: For learning a versatile technique, it's good to hone your picking accuracy. But I echo slim's advice that you should always let your ear be the judge rather than any "rules".
For avoiding the low E string on the up-stroke of a D chord -- the A is part of the chord, so it's fine: it just makes an inversion rather than a root-position chord -- you can work on the angle of your strum, so that you just miss the string. Another way is to drag across the strings and stop against the E string itself.
Another thing you can do, possibly in combination with the above, is muting the unwanting string. You could stretch your pinky up and touch it or wrap the thumb over the top. Or, since your strumming with your fingers, you could mute it with your thumb and strum that chord with just finger motion.
It'll take some experimenting to find a way that works for you.


Is there a simple way to get the numbers of squares that can fit into an integer N in descending order starting with sqrt(N)?

Question: To make things clear, consider the example of $$N=143= 11^2 + 4^2 + 2^2 + 1^2 + 1^2$$
Is there a way to predict how many squares will add up to N=143 in descending order without finding the squares if the only operation used is taking the sqrt(N), then sqrt(N-a^2), then sqrt(N-a^2-b^2)..?
Answer: As I understand the question, you want to know the maximum run-time of your algorithm for expressing a number $N$ as a sum of decreasing squares. You are not looking to minimise the number of squares (which is where the four-square theorem discussed in another answer might come in handy).
My first approach will be to consider the "worst case scenario." It is rather a naive way, but does give us an upper bound to the run-time.
In the "worst-case scenario" $N=k^2+(k-1)^2+...+2^2+1^2=\frac{k(k+1)(2k+1)}{6}\approx \frac {k^3}3$
This would give a run-time of $k\approx (3N)^{\frac 13}$
The problem is that this approach overestimates the run-time significantly!
My second approach is a recursive one.
Let $T(n)$ be the run-time for your algorithm starting with the number $n$.
It can be shown quite easily that:
$T(1)=1$
$T(2)=2$
$T(3)=3$
Linear? Of course not!
$T(4)=1$
$T(5)=2$
Once again let's look at a worst case scenario - where you have the largest possible residue after subtracting the first square. This is when $n$ is just one less than a slightly larger square.
If $n=(k+1)^2-1$, then we subtract $k^2$.
The result is $(k+1)^2-1-k^2=k^2+2k+1-1-k^2=2k$
So $T((k+1)^2-1)\le 1+T(2k)$
Since $n=(k+1)^2-1$, we have $n+1=(k+1)^2 \Rightarrow k=\sqrt{n+1}-1$
$T(n)\le 1+T(\sqrt n)$
This is still quite tricky...
...but it is true to say that $\sqrt n \le \frac n2$ for all $n > 4$
So our sequence is $T(n)\le 1+T(\frac n2)\le 1+1+T(\frac {n}4) \le ...$
Again an upper bound can be found by asking how many times must we halve until we get to $T(3)$
$n(\frac 12)^k=3 \Rightarrow \frac{n}3=2^k \Rightarrow \log_2(\frac{n}3)=k  \Rightarrow T(n) \le \log_2(\frac{n}3)+3 \le \log_2(n)+2$
That gives what is still an upper bound $T(n)\le \log_2(n)+2$
Comment: exactly, I am not looking to minimize the number of squares because we can express a number as a sum of 2 squares or 3 or 4. I just want to get the total number of squares but in descending order ( we start with sqrt(N)=a, then get sqrt(N-a^2)...). I don't even want their numerical value for now, just the total number of squares. We get fewer squares if we start from sqrt(N)=a then work our way down as opposed to starting from 1+2^2+3^2...=N.
Answer: If $N = \lfloor \sqrt{N} \rfloor^2 + R$, then $R \leq N/2$ for $N > 3$.  Therefore the number of iterations is $O(\log N)$.
Answer: There is this theorem "Lagrange's four-square theorem"(https://en.wikipedia.org/wiki/Lagrange's_four-square_theorem)
that predicts that every natural number can be expressed as the sum of four squares.
Comment: I know that but I am interested in the general case. It can be 3, 4 or 5 or more. You take a number, you take its sqrt(N)= a, then get (N-a^2) and take its sqrt (N-a^2)=b...we may end up with more than 4 like in the example I gave.
Comment: @user25406 I see. It seems like a very difficult question.


Lagrange's Theorem ($f(b)-f(a)=f'(c)(b-a)$) problem

Question: Let's consider function $f(x) = \sqrt[4]{x}$ on the interval $[a,b]$ with $a,b > 0$. Find point $c \in (a,b)$, for which the condition of the Lagrange Theorem holds. (Don't forget to check that the found point is inside of $[a,b]$).
So the Lagrange condition is the following: $f(b)-f(a)=f'(c)(b-a)$.
I have found the solution like this:
$$\sqrt[4]{b}-\sqrt[4]{a} = \frac{1}{4 c^{3/4}}(b-a)$$
Which leads me to the following solution:
$$\frac{(b-a)^{4/3}}{(1/4)^{4/3}(b^{1/4}-a^{1/4})^{4/3}}$$
And this apparently is not a correct answer. Plus I have not checked that this point is in $(a,b)$.
Here is how you check:
$$a = \left(\frac{(\sqrt[4]{a} + \sqrt[4]{a})(\sqrt{a} + \sqrt{a})}{4}\right)^{4/3} < \left(\frac{(\sqrt[4]{a} + \sqrt[4]{b})(\sqrt{a} + \sqrt{b})}{4}\right)^{4/3} < \left(\frac{(\sqrt[4]{b} + \sqrt[4]{b})(\sqrt{b} + \sqrt{b})}{4}\right)^{4/3} = b$$
Comment: Should be $4$ in denominator, not $1/4$.
Comment: For $c\in(a,b)$, $f$ is concave, $f'$ is decreasing, and $f'(a)>\frac{f(b)-f(a)}{b-a}>f'(b)$, so by IVT applied to $f'$, $c$ must be between $a$ and $b$. Doing it by algebra looks tricky...
Comment: thanks @NicolasFRANCOIS
Answer: The derivative is $f'(x)=x^{-3/4}/4$, so the point $c$ satisfies
$$
4\frac{b^{1/4}-a^{1/4}}{b-a}=c^{-3/4}
$$
Note that the solution is unique. Raise both sides to the power $-4/3$ and find
$$
c=\left(\frac{b-a}{4(b^{1/4}-a^{1/4})}\right)^{\!4/3}
$$
Your computation is indeed correct.
There is no need to prove that $a<c<b$, because Lagrange's theorem tells us this holds.
If you have to go with the torture, set $u=a^{1/4}$, $v=b^{1/4}$ and prove that
$$
\left(\frac{v^4-u^4}{4(v-u)}\right)^{\!4/3}<v^4
$$
which becomes
$$
\frac{v^4-u^4}{4(v-u)}<v^3
$$
that is,
$$
v^3+uv^2+u^2v+u^3<4v^3
$$
Let $u/v=w$, so $0<w<1$. Then the inequality becomes
$$
w^3+w^2+w-3<0
$$
The polynomial factors as $(w-1)(w^2+w+3)$ and the latter factor has no roots. So the only root is $1$ and the polynomial assumes negative values for $w<1$.
Do similarly for the inequality $c>a$.


Why would expectations of students vary largely between instruments?

Question: I have been learning flute for about 3 years, and we (myself and fellow flutists) are basically expected to play whatever we are presented with at the band we play in. We would be expected to play fairly complex rhythms, along with your standard multiple key signatures.
However, some of the other instrument players (particularly the low brass, and I mean whole instrument sections, not just individual people) in the band seem to have dramatically lower standards. They will often say that the piece we are playing is too hard due to relatively basic rhythms, or because of key signatures that their instruments "aren't supposed to play in" (for example, they complain when there are any sharps, or sometimes even no sharps or flats. As for what they are "supposed" to play in, I have no idea). I'm pretty sure that if I said I can't play a piece because it wasn't in the key flute is "supposed" to play in, I'd be given a reality check quick smart by my teacher.
They can even get away with not knowing fingerings for notes, something that I'd think is easier than flute, since they only have a few valves (except trombone, of course) to remember. Either way, I know that people in other sections not knowing fingerings is not really acceptable in our band once you have been learning the instrument for a while.
These people have been playing for as long as, if not longer, than I have, yet they don't seem to be expected to have equivalent skill of the other instrument players in the band.
Why would this be so? Are those said instruments simply much harder to learn, or is it because of how those players have been taught?
Answer: Brass have their overall sweet spot around 2 flats, strings about 2 sharps.  That's because their layout is based on some natural notes related by pure intervals.  Essentially those you can play while leaving valves or fingerboard alone.
In contrast, many woodwinds have a sort of "piano keyboard" with the difficulty being more or less that of working with "black" and "white" keys rather than having some central notes related by pure intervals.  They can be designed to be comparatively key-neutral by designing them around an equally-tempered scale.
That's not possible with brass in general (of course, trombones have no issue here).  And it's not usual with strings (they are tuned using pure fifths from A, and neither tempered nor alternate tunings are almost ever employed).
At any rate, the results are quite better out of the box if it's not the brass that has to play in unusual keys: while one can work with the embouchure to make uncommon scales work out well, it requires much higher skill than playing unusual keys reasonably nicely with other instruments.
Comment: Intonation is a very undervalued point.  A lot of pitch compensation seems to happen almost subconsciously, at least for me on trumpet, so when you are playing a horn that is in tune you may find things are just easier, and you have greater range and endurance.  Playing in an off-key or a horn with intonation issues will wear you out faster and affect your tone, and it can be very easy to overlook why this is happening.  This is probably only more of an issue if you are already comfortable adjusting intonation via embrochure, but I'm sure it affects everyone to a degree.
Comment: While I'm not a brass player, I've looked at the theory of brass instruments and it's quite obvious that it's impossible to make a brass instrument that's in tune in all notes. You finger either open (all valves up) or a fourth below it (valves 1 and 3 down) and you expect Valve 2 to drop a semitone in both cases??!! In theory you need 1/3 more tube for the second case, so it's entirely unsurprising that lowering by a tritone is sharp on the brass instruments. http://en.wikipedia.org/wiki/Brass_instrument Sure, you can use the embouchure, but I've often wondered how much correction you get.
Comment: @steveverrill - on trumpet, the 3rd valve slide helps with this.
Comment: If, as well as looking at the theory of brass instruments you also look at the practice of brass instrument manufacture, you'll discover finger-operated tuning slides on trumpets, and ingenious systems of "compensating valves" on the larger instruments, which contrive to make (1 + 2 + 3) MORE than the sum of 1, 2 and 3 individually.
Answer: I've been playing trombone for a while and I think I'm fairly well positioned to answer some of your points:

They will often say that the piece we are playing is too hard due to relatively basic rhythms...

The effort needed to articulate a distinct note is greater on a larger instrument - this complicates playing complex rhythms, as the end of one note can more easily start to get in the way of the start of the next. For trombone, combine this with the additional effort needed to reach the next slide position.

... or because of key signatures that their instruments "aren't supposed to play in" (for example, they complain when there are any sharps, or sometimes even no sharps or flats. As for what they are "supposed" to play in, I have no idea).

user19212 is quite right about brass instrument construction favouring one or two particular keys. On trombone, the reason for preferring flats to sharps or naturals isn't so much a matter of tuning - it's a matter of mechanical convenience. Generally speaking, it makes sense to stay near the top of the slide and move the slide around as little as you can get away with. Except in the rare cases where you're all the way out on 7th, you can always go one slide position further out to play a flat, but if the slide is at 1st position (i.e. closed) and you need to sharpen a note, you can't go one position further in - you have to head out all the way to 3rd / 4th / 5th and switch up a register, which is more of an effort.
Also, there's a matter of familiarity - if most pieces you play are written in the keys that favour your instrument, it becomes harder to navigate an unfamiliar key. I find it much easier to play a G flat major scale than an F sharp major scale even though the two are enharmonically equivalent. Both keys are fairly uncommon, but I'm familiar with the flats more than the sharps.

They can even get away with not knowing fingerings for notes, something that I'd think is easier than flute, since they only have a few valves (except trombone, of course) to remember. Either way, I know that people in other sections not knowing fingerings is not really acceptable in our band once you have been learning the instrument for a while.

This sounds like something that depends mostly on the standard of the ensemble you're playing with, and what their expectations are. Having said that, there are usually at least 2 fingerings / slide positions where any one note can be played on most brass instruments (by using different registers) and sometimes it makes sense to use a different one, e.g. to avoid moving the slide or to allow for better tuning. Also, due to variations in construction of some brass instruments, there may be even more options to consider - e.g. some tubas have a 5th valve.
All of these are issues that can be overcome with sufficient practice, obviously.
Answer: The amount of air that a flautist is moving and a lower brass player is moving are substantially different. It's much quicker to articulate on a flute.
Also, you have to barely move your fingers to change notes, where brass has to move the full height of the piston. When it comes to knowing the fingering, flutes look up a flute fingering chart, and they're done. It's the same for two octaves and then the upper register is still related to the fingering of the lower octaves. A tuba has to look up the right sort of fingering chart - B flat vs. E flat, three/four/five valves, compensating vs. non-compensating. And some of these overlap in some places and differ elsewhere, and a G might be different in every octave, for example.
Other have discussed the mechanical restrictions on brass.
Answer: There are a couple of factors here.
Some instruments are similar, but vary in terms of their technical difficulty
For example, if you were to compare the flute, clarinet, oboe, and bassoon, the flute has the least amount of variation between registers, required alternate fingerings, and keys in general. The clarinet has more keys, different fingerings across registers, and slightly more resistance on articulation. The oboe requires regular use of half-holes and unintuitive fingerings and has a much higher pitch variability. The bassoon has the most complex fingering system, high pitch visibility, and more physically difficult to perform fingering shifts.
While all four of these instruments are capable of performing similar feats of dexterity, in general it is slightly easier to play very fast, technical pieces on the flute, and also slightly easy to perform acts of transposition because of register symmetry.
Some instruments have difficulty tiers based on entirely different mechanics
For a very obvious example, consider a flute vs. a piano. Some of the challenges in flute (tone production, articulation, intonation) don't even exist when playing piano, while conversely the flute player needn't worry about multiple concurrent moving lines, pedaling, or consistent key pressure.
In other cases, players control similar factors using different mechanisms. Compare, for instance, the flute vs. the violin.
Tone production:

Flute: Breath support, embouchure, tongue position
Violin: Bow, controlled by right hand and arm

Intonation:

Flute: Angle of air, embouchure, length of instrument
Violin: Left
hand finger position on string, string tension

Articulation:

Flute: Tongue, breath control
Violin: Bow pressure, angle of hair, bowing speed

Note Selection:

Flute: both hands work together to play one note
Violin: one or more fingers work together with the bow to play one or more notes

As you can see, all these mechanisms are very fundamentally different, so the kinds of things that are "hard" on flute might not be the kinds of things that are "hard" on violin, or on brass instruments.
Some players are just not often presented with challenging parts
For a mixture of legitimate acoustic reasons and less legitimate ignorance reasons, many composers don't write very demanding technical parts for certain sections. Your tuba and euphonium parts are far more likely to play stable, consistent rhythms in a more narrow range, while higher instruments are more likely to get moving, technical parts because it's easier to hear moving parts on the top of a chord, and also because that's what they're most familiar with. Yes, it's kind of circular.
That doesn't mean that they are incapable of doing these things, or even that their instruments are poorly suited for them. It just means they are less likely to have experience with them if they're not practicing outside of rehearsal setting.
Conclusion
While there are differences in technique across instrument sections, none of these are excuses for playing in different key signatures or counting complex rhythms.
Modern wind instruments, including brass instruments, are fully capable of playing in all keys. String instruments are also fully capable of playing in all keys. While there are some keys that are "easier" than others for most instruments, if anything it's actually less work to play in distant keys on brass and strings than on woodwinds. All the ratios between notes are the same, regardless of what key you're playing in, and the intervals between those notes are much more apparently reflected in the fingerings for brass and string players than for woodwind players.
Yes, it's harder to jump around and tongue fast on brass, but it doesn't take very much searching to find virtuosi playing Flight of the Bumblebee on just about any instrument. This is not to say everyone needs to be able to do that, but key signature complaints are just them being lazy. Go practice your scales, learn your pedal tone fingerings, and work on some counting, low brass!
Answer: To my ears, this is not about the instruments but about people. What I hear the brass players saying is more like "this is a difficult rhythm and I am too lazy to spend the time to learn it", or "this is a difficult key and I am too lazy to learn to play it".
It would be a completely different thing if the player said "this is too difficult for me right now, let me work on it a few weeks and if does not work out then, maybe we could find something easier to play".
The person that should take of this is the band leader. It might be true that the brass players are weaker, and the music is a challenge slightly above their competence. At the same time he tries to challenge the flutes to raise to their challenges. Balancing this kind of different levels in an orchestra is not an easy thing to do.
Comment: I want to somewhat agree with this answer. While there are many points that can be made as to why brass has it harder than woodwinds for some parts I think using excuses like "it's too hard" is always the wrong approach and should not be accepted or enforced by the teacher. Playing in a band should be about learning and overcoming these "too hard" parts. You need them for there to be a challenge and improvement.


What protocols does gateway convert?

Question: I've read that:

Gateways are basically protocol converters, facilitating compatibility
between two protocols and operating on any layer of the open systems
interconnection (OSI) model.

I don't understand what protocols gateway converts. Why is it important to convert protocols? Isn't TCP/IP protocol stack  common for all devices that take part in network transmission of data?
Comment: Please cite the source of the quote so that the relevant context is known. "Gateway" is a very broad term which is used in different ways in different contexts. But what you cite would for example apply to gateways translating between IPv4 and IPv6 (IP protocols), between SIP, POTS or H.323 (telephony protocols), between HTTP/2 and HTTP/1 (different versions of HTTP protocol) etc.
Comment: @Steffen Ullrich Here's the [source](https://internetofthingsagenda.techtarget.com/definition/gateway#:~:text=Gateways%20are%20basically%20protocol%20converters%2C%20facilitating%20compatibility%20between%20two%20protocols%20and%20operating%20on%20any%20layer%20of%20the%20open%20systems%20interconnection%20(OSI)%20model.)
Answer: "Gateway" is a broad term which is used in different ways in different contexts. "Protocol" is a similar broad term with context specific meanings.
What you cite would for example apply to gateways translating between IPv4 and IPv6 (different IP protocols), between SIP, POTS or H.323 (different telephony protocols), between HTTP/2 and HTTP/1 (different versions of HTTP protocol), WebSockets and plain TCP sockets (different protocols for bidirectional communication) etc.
Note that other common uses of the term Gateway in the context of network don't involve converting protocols. For example Secure Web Gateway or Secure Mail Gateway keep the application protocol but inspect the protocol payload. For even more meanings see Wikipedia: Gateway.

What protocols does gateway convert?


How to do a simple group by without any statistics like mean or count in Pandas?

Question: I have a dataframe with many columns.
I want to do something like the summary tool in Alteryx. i.e. a simple group by. I am not interested in the statistics like mean or count or size.
I dont want a hierarchial output
How can I do it?
df.head()

      Unnamed: 0    home_odds    draw_odds    away_odds  country    league            datetime             home_team        away_team      home_score    away_score
--  ------------  -----------  -----------  -----------  ---------  ----------------  -------------------  ---------------  -----------  ------------  ------------
 0             0         1.36         4.31         7.66  Brazil     Copa do Nordeste  2020-02-07 00:00:00  Sport Recife     Imperatriz              2             2
 1             1         2.62         3.3          2.48  Brazil     Copa do Nordeste  2020-02-02 22:00:00  ABC              America RN              2             1
 2             2         5.19         3.58         1.62  Brazil     Copa do Nordeste  2020-02-02 00:00:00  Frei Paulistano  Nautico                 0             2
 3             3         2.06         3.16         3.5   Brazil     Copa do Nordeste  2020-02-02 22:00:00  Botafogo PB      Confianca               1             1
 4             4         2.19         2.98         3.38  Brazil     Copa do Nordeste  2020-02-02 22:00:00  Fortaleza        Ceara                   1             1

I want a simple grouped by these two columns
e.g.
    country    league
--  ---------  ----------------
 0  Brazil     Copa do Nordeste
 1  World      World Cup
 2  Australia  FFA Cup
 3  Australia  A League
 4  Brazil     Serie A

What is the correct code for it?
Comment: Kindly provide a simple reproducible dataframe input. Your output has World Cup. Where is that from ? Provide data that suffices. Meanwhile it is possible that you are thinking of drop_duplicates function
Answer: If you want to create a dataframe with two columns which shows which country has which league, then select the relevant columns and .drop_duplicates method:
out = df[['country', 'league']].drop_duplicates()

But if you want to create a dataframe that keeps data from the other columns, you might want to do:
out = df.groupby(['country', 'league']).agg(list)

Answer: You can try using drop_duplicates() function. For example in first dataframe below, you can see 13 records and in second only 6. It was thanks to df = df.drop_duplicates()


Surefire marks tests as failed when they set SecurityManager

Question: I have some tests that need to check if the main code did a System.exit(...). This works very nicely with suggestions from https://stackoverflow.com/a/309427/1023341. But when running these tests in Jenkins (in stead of in my IDE Eclipse) and later when trying them on the command-line using Maven-Surefire (as Jenkins does) the tests fail without telling me why. It only tells me: Error occurred in starting fork, check output in log.
Comment: Can you elaborate why your code is using System.exit(..) ?
Comment: Thanks for your concern. I know I should not use System.exit(...) but as I'm using a legacy library that still needs migration there is currently no (cheap) way around this. (It's funny that when ever the System.exit(...) comes up that people ask this question...)
Comment: I would suggest to check this: https://todd.ginsberg.com/post/testing-system-exit/
Comment: Indeed, nice small little solution, though I like the lingo of https://github.com/stefanbirkner/system-lambda better. (catchSystemExit)
Answer: When setting a SecurityManager during JUnit (5) using System.setSecurityManager and using Surefire plugin, you should restore the SecurityManager after the test.
SecurityManager origSecurityManager = System.getSecurityManager();
try {
     // ... code under test here ...
} finally {
     System.setSecurityManager(origSecurityManager);
}

or some other more suitable form. This makes sure that Maven-Surefire-plugin stays happy.
Edit for suggested pre-baked solutions:
There are two pre-baked libraries for this:

junit5-system-exit
system-lambda

As the name suggests: the system-lambda is a Java 8+ solution. Both are JUnit 5 compatible. My personal preference lies with the lambda solution.
More background information
Comment: This is the technical background but indeed there are solutions in libraries as @khmarbaise suggested


connection with couchdb server interrupted while uploading a file

Question: What happenes if the connection is interrupted during a document upload? The document isn't saved to server? or it is saved partially? The document contain an image/jpeg attachment in base64
Answer: Partial writes are not allowed, so you'd need to re-write it.


Mean Survival Time: Comparison of Continuous and Discrete Time

Question: First, the expected survival time when time is time to event is treated as a continuous r.v. is given as the following:
$$\int_0^{\infty} S(t)\, dt$$
The formula for the mean residual survival time $\text{mrl}(u)  = E(T -u | T>u)$ is given by
$$\frac{1}{S(u)}\int_u^{\infty} S(t)\, dt.$$
Can anyone explain the logic of dividing by $S(u)$?
For discrete time, this step does not appear needed (cf related question). Why?
Thanks!
ADD after Henry's explanation:
Lets say I have discrete time (12 months with the following hazards and Survival).
month<-seq(0,12)
h_x<-c(0,0.115706673,0.110186514,0.115769107,0.108296623,0.08908868,0.082548228,0.060146699,0.048112058,0.042197452,0.036919831,0.024691358,0.012787724)
S_x<-c(1,0.8843,0.7869,0.6958,0.6204,0.5651,0.5185,0.4873,0.4639,0.4443,0.4279,0.4173,0.4120)

plot(month,S_x,type="b")

1) Is the mean (truncated) lifetime sum(S_x[2:12]) #6.3117?
2) Lets say that we are know that a person survives up to 5th month (start of 5) i.e. they get through 4 complete months and we now want to estimated their mean (truncated) residual life. So, $\gamma$ =7 Is this computed as sum(S_x[5:12])/S_x[5] #6.358317 since 6.358 < $\gamma$+1 ?
Comment: I'm a little unsure of the notation, but I think $\prod_{k=t}^{j}\left(1-h(k|\mathbf{x})\right)$ corresponds to $S(t)/S(u)\ dt$.  Notice how the former is automatically normalized to $1$ for $j\lt t$ and, similarly, that $S(t)/S(u)\ dt = dt$ at $u=t$.  Therefore the answer to your question must be lurking in the definition of $h$.  Could you provide that definition so that this pair of questions can stand on their own?
Comment: Not sure I follow @whuber. Can you explain more?
Answer: $S(t)$ is the probability of surviving to time $t$ or beyond.
So the probability of surviving to time $t$ or beyond given that you have survived to time $u$ (with $u \le t$) is $\frac{S(t)}{S(u)}$, and so this is also the probability of a residual survival time of $t-u$ or beyond after time $u$.
This is implicit in your earlier discrete question, which could have looked like $$\frac{\prod_{k=0}^{j}\left(1-h(k|\mathbf{x})\right)}{\prod_{k=0}^{t-1}\left(1-h(k|\mathbf{x})\right)}$$ but this is more easily written as ${\prod_{k=t}^{j}\left(1-h(k|\mathbf{x})\right)}.$
Comment: @B_Miner: To expand briefly on Henry's nice answer, the formulas you provided in the question are completely general in the sense that they hold for *all* distributions of nonnegative random variables.
Comment: Your extended question is slightly spoilt by R starting counting at 1 not 0.  I would given `sum(S_x[2:13])` (6.724) and `sum(S_x[6:13])/S_x[5]` (6.022).
Comment: @B_Miner: As events $[T>x+t] ∩  [T>t] = [T>x+t]$ because $[T>x+t] \subset  [T>t]$
Comment: @Henry: Hope to revisit this as I think that the extended question above 1) Is the mean (truncated) lifetime sum(S_x[2:12]) #6.3117? was misunderstood. I was re-reading this and wonder if my use of the word truncated confused. I was asking how to compute the mean lifetime (which is the mean of the truncated distribution since the survivor function does not go to zero). Should this not be a summation of the entire survival curve: sum(S_x[1:13])/S_x[1] where the denominator is typically ignored since it is always equal to 1.
Comment: This is really a matter of interpreting the data in the question.  Suppose you had started with `h_x <- c(0,1); S_x <- c(1,0)`. Then the probability of surviving to the start of the first month is $0$.  So I would say the expected lifetime was zero, i.e. `sum(S_x[2:2])/S_x[1]`.
Comment: I was reading this: www.data-miners.com/resources/Will%20Survival.pdf page 3. and this support.sas.com/resources/papers/proceedings10/252-2010.pdf page 2. In both cases (first is discrete time, second is continuous) it seems that the calculation for the mean lifetime (truncated/restricted or not) started at summing or integrating at t=0, which should include 1, the survival at t=0. So, I am confused if I am predicting mean life (not residual) in the first case I gave as 7.7 or 6.7.
Comment: Henry - I will post this as a new question.
Comment: Henry: I posted an addition to my question to help clarify. Many thanks!
Comment: should the mrl be sum(S_x[6:13])/S_x[6] as well?
Comment: I would say not, for same reason the first answer is `sum(S_x[2:13])/S_x[1]` not `sum(S_x[2:13])/S_x[2]` nor `sum(S_x[1:13])/S_x[1]`
Comment: Should one be able to look at the MRL in the case of continuous r.v. T in terms of simple conditional probability? For example P(T>x+t | T>t) = P(T>x+t $\cap$ T>t) / P(T>t). What happens to the second part of the numerator to get P(T>x+t) / P(T>t)?
Comment: Henry, I am revisiting my inability to completely grasp discrete time survival analysis. I posted a fresh question about how to calculate S(t) here: http://stats.stackexchange.com/questions/60036/discrete-time-survival-analysis-correct-way-to-write-survival-function. Is it true given your answer "S(t) is the probability of surviving to time t or beyond" that you regard S(t) as P(T>=t)? Note, the equal sign.


WPF XAML ListBox bind to array

Question: So i have a float array which i want to have as ItemSource in a ListBox.
Inside the ItemTemplate i have a progress bar, that should bind its Progress value to the given float value. Yet i can't ever see that the values are actually bound to the Progress property.
The xaml code (i don't know whether i'm wrong but i expected that there's a implicit cast from float to double):
<ListBox ItemsSource="{Binding CoreLoads, Mode=OneWay}" BorderThickness="0">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type sys:Double}">
            <StackPanel>
                <ctrl:MetroProgressBar Orientation="Vertical" Progress="{Binding}" ExtenedBorderWidth="0.2" Width="30" Height="50" VerticalAlignment="Center"
                                       HorizontalAlignment="Center" BorderBrush="Black" BorderThickness="2" Background="White" Margin="5"/>
                <TextBlock Margin="0,3,0,3" HorizontalAlignment="Center" Text="{Binding LastUpdateTime, StringFormat='{}{0:hh:mm:ss tt}', Mode=OneWay}"
                           DataContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

xmlns:sys="clr-namespace:System;assembly=mscorlib"

and the property itself:
public double[] CoreLoads
{
    get { return cpuManagement.ProcessorInfo.LoadPercentages; }
}

Note: The progress bar i'm using is a custom control and inherits from System.Windows.Controls.Control.
Problem seems to be that the values of the array are ok but when bound to a TextBlock the values are 0, so the progress of the progress bar is always 0. So, am i having a correct data template for a double array? Or should i change to another type of collection?
Comment: Try data binding to the [`ProgressBar.Value` Property](https://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.rangebase.value(v=vs.110).aspx).
Comment: @Sheridan I should have mentioned that the progress bar i'm using is a custom control that inherits `System.Windows.Constrols.Constrol`. So there is no value property (in this case one could say `ProgressBar.Value` = `MetroProgressBar.Progress`.)
Comment: So, you want to bind a value of the progress bar to the selected value of your ListBox?
Comment: @floyd Yes, that is exactly what i want to do. But i don't know whether my approach is correct since you would normally provide a data type for the template and bind to its members (?) (i'm pretty new to wpf).
Answer: I guess you should create a property in a ViewModel(assuming you're using MVVM pattern) which will represent selected value of the ListBox:
    private double selectedCoreLoad;
    public Double SelectedCoreLoad
    {
        get
        {
            return selectedCoreLoad;
        }
        set
        {
            if (selectedCoreLoad != value)
            {
                selectedCoreLoad = value;
                RaisePropertyChanged("SelectedCoreLoad");
            }
        }
    }

Then, you should bind selected value of the ListBox to this property:
<ListBox ItemsSource="{Binding CoreLoads, Mode=OneWay}" SelectedValue="{Binding SelectedCoreLoad, Mode=TwoWay}" BorderThickness="0">

<ctrl:MetroProgressBar Orientation="Vertical" Progress="{Binding SelectedCoreLoad}" ExtenedBorderWidth="0.2" Width="30" Height="50" VerticalAlignment="Center"
                                       HorizontalAlignment="Center" BorderBrush="Black" BorderThickness="2" Background="White" Margin="5"/>

UPD
Use ObservableCollection instead:
private ObservableCollection<Double> coreLoads;
public ObservableCollection<Double> CoreLoads
{
    get { return coreLoads; }
    set
    {
        coreLoads = value;
        RaisePropertyChanged("CoreLoads");
    }
}

Comment: First of all thanks for pointing out a typo in my code. And second tried this and i found out that xaml is actually working with `System.Single` instead of double/float values. After writing a converter i'll check if it will work.
Comment: Now after testing it still does not show anything. Maybe i'll try it via code, even though that would not be THE solution using MVVM.
Comment: Are you sure that you've implemented INotifyPropertyChanged interface in  the base class of your ViewModel? I would also try to check out whether the SelectedCoreLoad property changes when you're selecting new value in your ListBox.
Comment: INotifyPropertyChanged is implemented in the base class of my view model. But actually the value of SelectedCoreValue is never accessed using `SelectedValue`. With `SelectedItem` there are read and write attempts (always with value 0). But i identified the problem: the values returned in the array are ok but when binding them to a `TextBlock` they are always 0 instead of e.g. 6.545, 4.234, 0, 65.123.
Answer: So found the answer: ListBox seems not to like arrays as ItemsSource. After changing the source to a double-list everything works.
public List<double> CoreLoads
{
    get { return new List<double>(cpuManagement.ProcessorInfo.LoadPercentages); }
}

WPF XAML ListBox bind to array


Meta filter: Layman/Academic/Real World

Question: I've stopped being here as frequently as before, or say, invest as much time as I used to in the start, also as I feel that slowly the ball started rolling.
However, now, as a not-fulltime-consumer, I notice that, given I prefer academic / graduate type questions, it already starts to become difficult to focus my preferred questions.
So I would like to suggest some kind of tagging, either

For Graduate/advanced questions, something like Acadamic. Anything that someone would not ask, if he had not finished a bachelor's degree. This should only tag questions above undergraduate level.
For "Beginners" questions, something like Layman. Anything that someone would not ask, if he had finished a Bachelor's degree.

Due to the definition, these two are mutually exclusive, so we would only need one of them. It's the question of what kind of becomes default, and what needs to be labelled. There's reasons for and against each of them, but I leave the floor open for discussions.
Secondly, I believe we also need a new meta label real world application or something along these lines, to allow people to include/exclude these types of questions.
Comment: I have no definite opinion on the tags your propose, but I also have trouble finding the graduate level questions I would be interested in. One partial workaround : look at unanswered question sorted by votes. In my experience, these tend to be graduate/advanced questions.
Answer: Atwood's reasoning is "meta tags do not describe the content -so they should be discouraged".  He was talking about the meta-tags "subjective", "beginner", "best practices". All useless, I agree with him. But: too little data, too small a sample, to generalize over the whole SE network, sorry, unacceptable, especially as the SE network has evolved from 2010 when that post was written.
And indeed, FooBar's approach is about meta-tags that will tell much about the content. I mean, under the tags "inflation", "unemployment", "macroeconomics", "monetary policy", we can see questions like

"Why economists care so much about inflation, and resist printing
  money in order to reduce unemployment? Isn't the creation of jobs more important
  ?

to

According to paper XXX, the duration of the effects of an
  unanticipated increase in money supply, depend critically on the
  degree to which the labor market is bilateraly regulated by contracts.
  The author presents data from three different countries where the
  effect lasted no less than the average wage contract duration in the
  economy, and in some cases, a bit more. In an attempt to rationalize
  this finding, as well as the fact that long-term contracts do exist,
  and extensively so, he builds a model where workers do not suffer from
  money illusion but value a constant nominal income because the
  internal costs of re-organizing consumption under a fixed nominal
  budget are lower than the bargaining and uncertainty costs from
  bargaining constantly with employers over wages (don't forget,
  bargaining may lead to lower wages also, even if this may come about
  through bargaining failure, search for work, unemployment spell, find work with lower pay). And
  the difference can more than offset the fact that the first situation
  leaves the workers exposed to surprises from the government, that may
  lower their real income. Now what I don't understand in his model is
  equation YYY...

Personally I would really want to have a way to filter such questions apart. Mind you, I am interested in both -but the mindset for each one is totally different.
My proposals:
1) I believe that the tag applied-economics considered by EnergyNumbers is useful. Granted, it may be a bit broad, but in partitioning separation with "applied econometrics" it will effectively include all "questions of the interested public" that deal with a specific economic phenomenon. These are the one big chunk of "layman" questions here (the other one is the "philosophical" strand and the various "what if" scenarios, but let's not rush here, and first see how these last sub-categories evolve in numbers).
2) I am in favor of creating a tag for the "academic/graduate" strand of questions. They are a world on their own -and let's not lose our heads over the name of the tag, let's call it exactly that : academic-graduate. No one will be confused.
Comment: Judging from the votes, there seems to be a fair bit of support for doing this. At what point does this question become resolved? Should we start doing this now?
Comment: Also, judging from the answers, it seems like people are generally in favor of the [tag:academic-graduate] tag but unsure about the [tag:applied-economics] tag. Should we start with just the [tag:academic-graduate] tag only?
Comment: @jmbejara We are still in the trial-and-error phase. I think we should try them out and see how they are being used.
Comment: I went ahead and added the tag for all questions without accepted answer on the front page, and will edit it into new questions. I guess if we potentially don't agree on some of the questions that get the label, it's best to open another question on meta.
Answer: We do have applied-econometrics, which covers some real-world applications. applied-economics doesn't exist yet; it might be too broad though.
As for academic / lay - they're meta tags, and strongly discouraged across the network. The problem is that they don't describe what the question is about, which is what the tags are for.
From that post:

From this point on, meta-tagging is explicitly discouraged.
  How can you tell you're using a meta-tag? It's easier than you might think.
  1. If the tag can't work as the only tag on a question, it's probably a meta-tag. Every tag you use should be able to work, more or less, as the only tag on a question. Meta-tags, like [beginner], [subjective], and [best-practices], are useless by themselves — they tell you nothing at all about the content of the question.
  2. If the tag commonly means different things to different people, it's probably a meta-tag.
Comment: Well, typical network sites are either for academic, or for normal questions (see also mathematics). Without listing the reasons for why meta-tags are bad, there is no way we can decide whether they fit our purpose here or not. I also think to remember that some sites (maths?) had *homework* as a tag, which clearly also is a meta tag.
Comment: From the same post: "*There's been a major uptick recently in tags that are not useful and just add noise.*" The suggested tags would clearly act the opposite, as helping to filter between posts I (and perhaps others) want to see and those we clearly **do not** want to see.
Answer: Alright, after seeing not too much of a response so far Ill post something myself to get the debate going.

It is very hard to phrase a tag for layman questions, if it's supposed to include undergraduate questions - without making them sound bad/degrading to undergraduates. They're not really layman, but what else would be inclusive: Beginners? Doesn't sound nice to me.
Also, I expect the share of users with few questions to be higher among those who ask layman questions. Hence, if we have to teach new users to use the tags, it might make more sense to teach the academic/graduates, as they're are both fewer in numbers, and tend to stay along longer

Emphasize vs hiding
For those like me who want to focus on graduate questions, having a favorites tag on graduate questions will emphasize these questions by background color, but  still display questions without the tag.
If we instead tag layman questions only, I would apply a filter then, effectively completely removing these questions.
I believe that we are still inclined towards an inclusive community, hence I suggest a tagging of academic/graduate questions.

Meta filter: Layman/Academic/Real World


Questions about the principles of Bayesian analysis + R

Question: Let's say I have a data of flywing lengths which is identically distributed (normal).
(data: https://seattlecentral.edu/qelp/sets/057/s057.txt).
I want to estimate the mean (theta).
I have to choose the model. Let's say the variance is measured 15.4.
To the prior I choose that
$$
\theta = 40
$$ .
I assume I can choose the variance as well, so I set it to 5.0
Now when computing the posterior I get
posterior mean of 4.205 and posterior variance of 0.118. (conjugate normal formula)
Am I even slightly on the right path?
If so, why does the variance data 15.36364 differ so much from the posterior variance?
Is this generally normal in Bayesian analysis or is the variance of something else than the estimator?
Answer:
I want to estimate the mean (theta). I have to choose the model. Let's say the variance is measured 15.4.
To the prior I choose that θ=40

The prior for θ is a distribution. If your prior distribution is a single value (i.e. the pdf of your prior is a Dirac delta function / the cdf of your prior is a step function), that's also where your posterior will be.
Do you instead intend to say that you chose the mean of your prior to be 40?

I assume I can choose the variance as well, so I set it to 5.0

Ah. It sounds like you did intend it to be a mean before. But what was the distribution of this prior? Normal?

Now when computing the posterior I get posterior mean of 4.205 and posterior variance of 0.118. (conjugate normal formula)

Hmm, presumably a normal prior then.

why does the variance data 15.36364 differ so much from the posterior variance?

Be careful -- don't confuse the posterior for the parameter with the distribution of the data.
The more data you have the more information you have about the mean. As you increase sample size the variance of the data stays about the same but the variance of the mean goes down. If you had a flat prior the posterior variance of the mean would be $\sigma^2/n$ (while if the prior had finite variance the posterior variance would be a bit smaller)

Is this generally normal in Bayesian analysis or is the variance of something else than the estimator?

It's also the case with frequentist statistics. The variance of a parameter's posterior (or a parameter estimate in the frequentist case) will decrease as you add information from the data, while the variance of the data will tend to the population variance.


How many feet of rope would be needed to wrap this device?

Question: So here is the problem. My dad designed this umbrella that is to be wrapped with rope. The rope is 1 inch thick, and the umbrella is made of poles that arch away from a center beam extending upward from the ground. My question is how many linear feet of rope would I need if I were to wrap the poles, under and over, starting from the leftmost (or rightmost) pole and working towards the center.

Larger view of the image with measurements
The red arrows are the rope, and 1 foot is to be left at the end after wrapping the rest of the umbrella. I only included arrows on two of the drawings. How would you go about solving this? Let me know if you need any more information. Thanks!!
Answer: The diagram doesn't have enough information to solve the problem.
The  answer is $$2\pi\cdot{R_i + R_o\over 2} N$$ where $R_i$ and $R_o$ are the radii of the innermost and outermost circles of rope, and $N$ is the number of windings around.  We have $R_i$, which is 1 foot (1 foot left unwrapped as shown in the upper left of the picture), or maybe 1 foot plus the thickness of the inner stem, and $R_o$, which is 14 feet (8+6 feet as shown in the upper right of the picture).
If the umbrella were flat, we would have $N$ equal to $R_o-R_i = 13$ feet divided by the thickness of the rope, which is 156 times around.  But the ribs are curved, so they are more than 13 feet long.  We need to know the length of the ribs, as measured with a flexible tape measure from the central stem to the end of one of the ribs.  If this length is $L$, then $N= L\div 1\text{ inch}$, and you should be able to use the formula above. But there is nothing in the diagram to tell us what $L$ is.
Still we can be sure that the rope will have to go around considerably more than 156 times, so each umbrella will need considerably more than $2\pi\cdot7\frac12\text{ feet }\cdot156 = 7,351$ feet of rope.
Comment: Thank you for this answer. Would the length of the ribs (L) be 14 feet? As shown by the top left image?
Comment: No, that's how long they would be if they were flat.  But they are sharply curved, so they are considerably longer than 14 feet. Also you need to measure only the part that will actually be covered by the rope.
Comment: O got it. I'll have to get that measurement and check this out. I'll let you know if this works! Thanks again.
Comment: does this formula account for the fact that the rope looses 1 inch in length each wrap as it gets closer to the center?
Comment: I'm not sure what you mean.
Comment: When we are wrapping the rope around the umbrella, each time we go across we get closer and closer to the center. Wouldn't that mean we need less rope after each pass?
Comment: Yes, and that's why the formula involves the length of the *average* pass, $2\pi\cdot\frac12(R_i+R_o)$, rather than the length of the longest pass, which is $2\pi\cdot R_o$, or the length of the shortest pass, which is $2\pi\cdot R_i$.


Fatal error: Uncaught Error: Call to undefined function mb_substr_count()

Question: Ao usar a funcao mb_substr_count , é retornado o erro abaixo.
Ja instalei o mb_substr usando o comando -> sudo apt-get install php-mbstring , e reiniciei , mas não resolveu..
Fatal error: Uncaught Error: Call to undefined function mb_substr_count()

Answer: Acesse o seu php.ini, pesquise extension=e olhe a lista de extensões. Se não houver algum com o nome mbstring, a extensão deverá ser instalada. Se a linha estiver comentada (se tiver ; na frente), então ela não está ativada ... remova o ; e reinicie o Apache
Answer: Há o comando php -m que lista os módulos instalados.
O comando abaixo vai buscar entre os módulos o mbstring e retornara algum resultado se ele já estiver sido instalado:
php -m | grep mbstring

Se não aparecer nenhuma mensagem no terminal, tente instalar com o comando:
sudo apt install php-mbstring

Após a instalação, reinicie o serviço com o comando:
sudo systemctl restart apache2

Answer: Resolveu instalando o mbstring via console
sudo apt-get install php7.2-mbstring


About $\int \csc(x) \, dx$

Question: One of the suggested proofs that I found to the $\int \csc(x) \, dx$ start with,
$$\int \csc(x) \, dx= \int \csc(x) \cdot \frac{\csc(x)- \cot(x)}{\csc(x)- \cot(x)} dx = \cdots$$
By graphing the function $f(x)=\csc(x)- \cot(x)$ I found that its have zeros for $x=2 \pi k$ for all $k \in \mathbb{Z}$.
So, I wonder if this proof it's valid for all $x \in \mathbb{R}$. Thanks for the clarification.
Comment: This integral is easy with the usual substitution $t=\tan(x/2)$.
Comment: Note that $\csc(x)$ is undefined at all such points anyways. And furthermore, values at individual, isolated points don't matter to integrals.
Answer: When you write $\int f(x)\,dx$ and expect to end up with something of the simple form $F(x)+C$, then you are only integrating $f$ over an interval on which $f$ is continuous. $\csc(x)$ has discontinuities at $k\pi$. So what has been done here is valid for say the interval $x\in(0,\pi)$.
The most general antiderivative for $\csc(x)$ would be $$-\ln\left|\csc(x)+\cot(x)\right|+C(x)$$ where $C$ is a function that is piecewise constant on intervals of the form $(k\pi,k\pi+\pi)$, and can take different values on different intervals.
Answer: The whole point of multiplying by $\dfrac{\csc x - \cot x}{\csc x - \cot x}$ is so that we get $$\int \frac{\csc^2 x - \csc x \cot x}{\csc x - \cot x} \, dx.$$  Then with a substitution of the form $u = \csc x - \cot x$, $du = (-\csc x \cot x + \csc^2 x) \, dx$, the integral is easily evaluated.  Now, if we want to know if the resulting antiderivative is valid, we would simply verify that its derivative equals $\csc x$, and look at its domain.  It is not difficult to see that $\log|\csc x - \cot x| + C$ is defined everywhere except when $\csc x = \cot x$, or $x = \pi k$ for $k \in \mathbb Z$, which also happens to be the domain of $\csc x$ itself.

About $\int \csc(x) \, dx$


Regression algorithm for weak correlated target and features

Question: I have a regression problem in hand. Dataset have 20 predictors and 1 target. Target is continuous and predictors are both categorical and continous. I performed a correlation test between continous predictors and target and found very week to negligible linear relation.
<code>#selecting numeric / continous variables
numCols <- unlist(lapply(employee_data_Imputed,is.numeric))
numVarDataset <- employee_data_Imputed[,numCols]
# Visualizing correlation
par(mfrow = c(1, 1))
corr <- cor(numVarDataset)
corrplot(
  corr,
  method = "color",
  outline = TRUE,
  cl.pos = 'n',
  rect.col = "black",
  tl.col = "indianred4",
  addCoef.col = "black",
  number.digits = 2,
  number.cex = 0.60,
  tl.cex = 0.70,
  cl.cex = 1,
  col = colorRampPalette(c("green4", "white", "red"))(100)
)

# 1. We found no strong relationship between target and predictors.
# 2. No strong correlation was found among predictors in dataset.
</code>

Here Absenteeism.in.hours is my target. My question is how should i approach this kind of data. What can be an appropriate machine learning technique for regression in this case.
Structure of my dataset is
<code>> str(employee_data_Imputed)
'data.frame':   740 obs. of  21 variables:
 $ ID                             : Factor w/ 36 levels "1","2","3","4",..: 11 36 3 7 11 3 10 20 14 1 ...
 $ Reason.for.absence             : Factor w/ 28 levels "1","2","3","4",..: 26 20 23 7 23 23 22 23 19 22 ...
 $ Month.of.absence               : Factor w/ 12 levels "1","2","3","4",..: 7 7 7 7 7 7 7 7 7 7 ...
 $ Day.of.the.week                : Factor w/ 5 levels "2","3","4","5",..: 2 2 3 4 4 5 5 5 1 1 ...
 $ Seasons                        : Factor w/ 4 levels "1","2","3","4": 1 1 1 1 1 1 1 1 1 1 ...
 $ Transportation.expense         : num  289 118 179 279 289 179 361 260 155 235 ...
 $ Distance.from.Residence.to.Work: num  36 13 51 5 36 51 52 50 12 11 ...
 $ Service.time                   : num  13 18 18 14 13 18 3 11 14 14 ...
 $ Age                            : num  33 50 38 39 33 38 28 36 34 37 ...
 $ Work.load.Average.day          : num  239554 239554 239554 239554 239554 ...
 $ Hit.target                     : num  97 97 97 97 97 97 97 97 97 97 ...
 $ Disciplinary.failure           : Factor w/ 2 levels "0","1": 1 2 1 1 1 1 1 1 1 1 ...
 $ Education                      : Factor w/ 4 levels "1","2","3","4": 1 1 1 1 1 1 1 1 1 3 ...
 $ Son                            : num  2 1 0 2 2 0 1 4 2 1 ...
 $ Social.drinker                 : Factor w/ 2 levels "0","1": 2 2 2 2 2 2 2 2 2 1 ...
 $ Social.smoker                  : Factor w/ 2 levels "0","1": 1 1 1 2 1 1 1 1 1 1 ...
 $ Pet                            : num  1 0 0 0 1 0 4 0 0 1 ...
 $ Weight                         : num  90 98 89 68 90 89 80 65 95 88 ...
 $ Height                         : num  172 178 170 168 172 170 172 168 196 172 ...
 $ Body.mass.index                : num  30 31 31 24 30 31 27 23 25 29 ...
 $ Absenteeism.time.in.hours      : num  4 0 2 4 2 2 8 4 8 8 ...
</code>
Answer: You have found that each individual continuous independent variable (IV) has at most a weak correlation with the dependent variable (DV). This does NOT mean that many IVs in combination will not explain much of the variance in the DV. Especially since the IVs are weakly correlated with each other, meaning that they may be contributing independent explanatory power.
Two other important factors that may help you:
1) Interactions between IVs may be important in explaining variance in the DV.
2) Your correlations ignore all the information contained in the categorical variables - which might be substantial.
Depending on your goals, a standard regression approach should be fine in this case; regularisation would probably be a good idea given your limited data. If you want to use a ML technique, random forests might work fine too, though again data limitation might be an issue.


Proof that there is no closed knight tour on a $3\ \times\ 8$ - board

Question: I want to prove that there is no closed knight tour on a $3\ \times\ 8$ - board by deleting $s$ vertices
 of the corresponding knight graph to get a graph with more than $s$ connected
 components (which would prove that it is not hamiltonian), but I did not succeed so far.
Who can help ?
Comment: Actually, the hint I wrote before is not entirely sufficient. Hopefully this observation helps anyway: suppose the board is the A1-C8 rectangle on a standard chessboard. Consider the squares A1 and C1. A part of the cycle through them is basically forced. Next, it might be a good idea to consider the square B1.
Comment: Maybe, there is another way to prove my claim, but the way I propose would be most elegant and easy to see, if it would work. A direct proof requires many cases here, and the danger is that some potential hamilton circle is overseen.
Comment: It is well possible (even likely), that my method is not possible in this case. Are there any more useful NECESSARY conditions for the existence of a hamilton-cycle ?
Answer: Do you have to prove it that way? It is not difficult to prove directly that there is no closed knights tour of a 3 x 8 board. You start with squares that have only two moves available, so you know both those moves must be part of any tour.
Label the squares $$\begin{array}{cccccccc}1 & 4 & 7 & 10 & 13 & 16 & 19 & 22\\ 2 & 5 & 8 & 11 & 14 & 17 & 20 & 23\\ 3 & 6 & 9 & 12 & 15 & 18 & 21 & 24\end{array}$$ There are only two moves from 1, so the path must include 8 1 6. Similarly, there are only two from 3, so it must include 8 3 4, and hence 4 3 8 1 6. Similarly, there are only two from 2, so it must include 7 2 9. If the path includes 4 9 and 6 7, then we have the closed path 4 3 8 1 6 7 2 9 4. Contradiction, so it can include at most one of 4 9 and 6 7. Similarly, it can include at most one of 4 11 and 6 11. But it must include one of 4 9 and 4 11 and one of 6 7 and 6 11. So wlog it includes 6 11 and 4 9. So we have 11 6 1 8 3 4 9 2 7.
Exactly the same argument in the right hand half of the board shows that 14 cannot be connected to both 19 and 21. It cannot be connected to 9 because that is already connected to 2 and 4, so it must be connected to 7.
Again by the same argument in the right hand half, 17 is connected to 22 and 24. Hence the only squares that can be connected to 10 are 5 and 15. Obviously 5 must also be connected to 12. 12 must also be connected to 13 (7 and 17 are unavailable). But 20 must be connected to 13 and 15, so we have the closed loop 20, 13, 12, 5, 10, 15, 20. Contradiction.
Comment: I accepted the answer because it is not likely that there is an easier method to proof the non-existence of a hamilton-cycle in this graph. Thanks for your effort.


sendmail working for some emails

Question: I use PHP to send email which uses sendmail.  I noticed that some emails are not being delivered with the below errors in /var/log/maillog
Example 1
stat=Unknown Sender
Example 2
stat=Deferred: 450 4.1.8 email@example.com: Sender address rejected: Domain not found
Example 3
stat=Deferred: 421 invalid sender domain 'testname.testurl.net' (misconfigured dns?)

Information about the server...
hostname - testname
/etc/hosts
127.0.0.1 - localhost.localdomain hostname
xxx.xxx.xxx.xxx - testname.testurl.net testname
::1 - localhost6.localdomain6 localhost6
Running Centos 5.8
Comment: Could you post **FULL** log entries? [Both `from=` and `to=` lines]
Answer: You have to make sure that all email related names and domains are existent and can resolve to your IP address. vice versa the IP address should be resolved to your domain.
Comment: How would I check this?
Comment: you have to set your hostname to something you can resolve via a public nameserver. in additio to that you have to tell your ISP that he should set the reverse dns entry for your IP address to your choosen domain / hostname

sendmail working for some emails


How to pass callback to View init?

Question: This example works, but if I need to add an init to do some prep work, I can't figure out hot to pass the callback. In the actual code I need to pass several parameters and do some other initialization.
import SwiftUI

struct Choices: View
{
    let choices = ["One", "Two", "Three"]
    @State var choice:String = "One"
    let callback: (String) -> ()

/*
init()
{
  // do stuff here
}
*/

    var body: some View
    {
        VStack(alignment: .leading)
        {
            ForEach(choices, id:\.self)
            { c in
                HStack
                {
                    Image(systemName: (choice == c) ? "checkmark.square" : "square")
                    Text(c)
                }.onTapGesture
                {
                    choice = c
                    callback(c)
                }
            }
            Divider()
        }.padding()
    }
}

struct ChoicesContentView: View
{
    @State var answers:[String] = ["","",""]

    var body: some View
    {
        VStack(alignment: .leading)
        {
            ForEach(0..<3)
            { i in
                Choices()
                {
                    ans in
                    print(ans)
                }
                Text("Selected: \(answers[i])")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ChoicesContentView()
    }
}

How to I pass the callback as a parameter?
Answer: It can be like
struct Choices: View
{
    let choices = ["One", "Two", "Three"]
    @State var choice:String = "One"
    let callback: (String) -> ()

    init(callback: @escaping (String) -> ()) {    // << here !!
        self.callback = callback
    }
// ...
}

or even with default value
init(callback: @escaping (String) -> () = { _ in }) {    // << here !!
    self.callback = callback
}

How to pass callback to View init?


Como modificar título do menu de um plugin no wordpress?

Question: Estou com um problema ao modificar o título do meu plugin no menu, preciso que o título principal fique diferente do segundo título, mas não estou conseguindo.
Como na imagem:

Meu Código:
public function menu(){
    add_menu_page('Gallery', __('Gallery', 'Galleries'), 'manage_options', 'gallery', array('view', 'main'));
    add_submenu_page( 'gallery', 'My Custom Page', 'My Custom Page', 'manage_options', 'my-top-level-slug');
    add_submenu_page( 'gallery', 'My Custom Submenu Page', 'My Custom Submenu Page', 'manage_options', 'my-secondary-slug');
}

Answer: Você pode manipular a variável global $submenu e mudar isso ali (também temos a variável $menu, mas não tem uso aqui):
add_action( 'admin_menu', function()
{
    add_menu_page(
        'Gallery',
        __('Gallery', 'Galleries'),
        'manage_options',
        'gallery',
        function(){ echo '
Principal
'; }
    );
    add_submenu_page(
        'gallery',
        'My Custom Page',
        'My Custom Page',
        'manage_options',
        'slug-1',
        function(){ echo '
Segundo
'; }
    );
    add_submenu_page(
        'gallery',
        'My Custom Submenu Page',
        'My Custom Submenu Page',
        'manage_options',
        'slug-2',
        function(){ echo '
Terceiro
'; }
    );

    // Trocar o nome de um submenu
    global $submenu;
    $submenu['gallery'][0][0] = 'Galerias';
});

E aqui, um var_dump da variável (resumido):
Array (
    [index.php] => Array (
            [0] => Array (
                    [0] => Home
                    [1] => read
                    [2] => index.php
                )
            [10] => Array (
                    [0] => Updates 5
                    [1] => update_core
                    [2] => update-core.php
                )
        )
    [edit.php] => Array ( [...etc...] )
    [upload.php] => Array ( [...etc...] )
    [edit.php?post_type=page] => Array ( [...etc...] )
    [edit-comments.php] => Array ( [...etc...] )
    [themes.php] => Array ( [...etc...] )
    [plugins.php] => Array ( [...etc...] )
    [users.php] => Array ( [...etc...] )
    [tools.php] => Array ( [...etc...] )
    [options-general.php] => Array ( [...etc...] )
    [gallery] => Array (
            [0] => Array (
                    [0] => Gallery
                    [1] => manage_options
                    [2] => gallery
                    [3] => Gallery
                    [4] => menu-top menu-icon-generic toplevel_page_gallery
                    [5] => toplevel_page_gallery
                    [6] => none
                )
            [1] => Array (
                    [0] => My Custom Page
                    [1] => manage_options
                    [2] => slug-1
                    [3] => My Custom Page
                )
            [2] => Array (
                    [0] => My Custom Submenu Page
                    [1] => manage_options
                    [2] => slug-2
                    [3] => My Custom Submenu Page
                )
        )
)

Answer: Quando você usa add_menu_page ele automaticamente cria um item com mesmo nome, você pode usar add_submenu_page e criar um item chamado Galleries, e excluir esse Gallery, o código fica mais ou menos assim:
public function menu(){
    add_menu_page('Gallery', __('Gallery', 'Galleries'), 'manage_options', 'gallery', array('view', 'main'));
    add_submenu_page( 'gallery', 'Galleries', 'Galleries', 'manage_options', 'my-top-level-slug');
   remove_submenu_page('gallery','gallery');
}


Trying to work on a paint program

Question: I am trying to get this working so only when I click a button on the side does it start drawing using the line tool.
I am new to Javascript/Jquery and I am trying to put these projects together.
http://jsfiddle.net/f7ZZM/99/

        <canvas id="paint" />

Answer: Change your html to :

                <canvas id="paint"></canvas>

Comment: I am looking to get the drawing program to work so when you click a button you draw straight lines and when its not clicked you draw normally. But thank you I have updated the fiddle with the HTML.

Trying to work on a paint program


Me ajude a consumir a API de NLU do IBM Watson

Question: Ontem eu assisti um video de um cara que consumiu a API de Natural Language Understanding do Watson (IBM cloud) com JS usando Node e ele fez coisas bem legais com ela...
Por outro lado eu estou tentando consumir e ver os resultados para fazer alguma coisa, mas nem sei se estou indo pelo caminho certo pois é a primeira fez que faço algo do tipo e pra piorar não tem documentação para C#
To usando o nugget pack IBM.WatsonDeveloperCloud.NaturalLanguageUnderstanding.v1
TokenOptions token = new TokenOptions
            {
                IamApiKey = "Minha ApiKey",
                ServiceUrl = "https://gateway.watsonplatform.net/natural-language-understanding/api"
            };

            var nlu = new NaturalLanguageUnderstandingService(token, "2018-12-19");

            var parametros = new Parameters { Text = "I'm Michael Jackson the king of POP"};

            var resultado = nlu.Analyze(parametros);

Até o momento o que estou fazendo é colocar um Breaking Point em "Resultado" e ver no que da e o que da não é bom! Resulta no seguinte erro:

IBM.WatsonDeveloperCloud.NaturalLanguageUnderstanding.v1.dll: 'One or more errors occurred. (The API query failed with status code BadRequest: Bad Request | x-global-transaction-id: ffea405d5d1cfc0efeae7731 | X-DP-Watson-Tran-ID: gateway02-4272846641 | error: {
    "error": "no features specified",
    "code": 400
  })'
Comment: A resposta da API é essa: `"error": "no features specified"`. Você não esqueceu de algo no meio do caminho?
Comment: Acho que não, em "parametros" eu tentei especificar o tipo de feature para pegar só as Keywords, mas ainda assim vinha a mesma resposta
Answer: Por ignorância minha, achei que a resposta fosse um erro quando na verdade eu apenas estava implementando da maneira errada.
A API pede que seja especificado ao menos uma Feature.... Antes de postar a duvida no fórum eu já tinha tentado passar uma feature, mas tinha feito isso de forma errada e por isso o "erro", então pesquisei mais e passei a feature da maneira correta, funcionou e ficou dessa forma:
TokenOptions token = new TokenOptions
        {
            IamApiKey = "Minha ApiKey",
            ServiceUrl = "https://gateway.watsonplatform.net/natural-language-understanding/api",
        };

        var nlu = new NaturalLanguageUnderstandingService(token, "2018-12-19");

        Features features = new Features();
        features.Keywords = new KeywordsOptions();

        var parametros = new Parameters { Text = "I'm Michael Jackson", Features = features };

        var resultado = nlu.Analyze(parametros).ResponseJson;

        Console.WriteLine(resultado);