What's Swift's "fromAfter" call in array slices?

Question: Swift 3 has upTo and through
which are noninclusive, inclusive respectively

func prefix(upTo: Int)
  Returns a subsequence from the start of the collection up to, but not including, the specified position.

.

func prefix(through: Int)
  Returns a subsequence from the start of the collection through the specified position.

for the other end it has from

func suffix(from: Int)
  Returns a subsequence from the specified position to the end of the collection.

which seems to be inclusive
What's the non-inclusive call at the far end??
    // sum the numbers before, and after, an index i...

    let lo = A.prefix(upTo: i).reduce(0,+)    // means noninclusive
    let hi = A.suffix(from: i+1).reduce(0,+)  // 'from' seems to mean inclusive

what's the call I don't know? It sucks to have to write from with +1.
Comment: A non-inclusive signature isn't in the Swift Standard Library reference and both the `suffix(_:)` and `suffix(from: )` references show inclusive examples, so it's not available in this version. I also saw no discussion that references a non-inclusive suffix, so it's not likely to be available any time soon.
Comment: I'm an ephemeral swift user so I usually prefer to leave an actual answer to someone who can give details, just as @dfri made.
Comment: Ah - brilliant info.  Maybe should paste it in as a decisive answer, @gelliott181 ?
Answer: There is currently no non-inclusive suffix method for for Collection types in the stdlib, but for this use case, you can readily implement your own by combining suffix(from:) with dropFirst(_:) (which, imho, better shows intent than from: idx+1), e.g.
extension Collection where SubSequence == SubSequence.SubSequence {
    public func suffix(after start: Index) -> SubSequence {
        return suffix(from: start).dropFirst(1)
    }
}

Applied to your example (separately sum numbers before and after a given partitioning number (or, index of), not including the partitioning one):
/* in this example, invalid indices will yield a full-array sum into
   lo or hi, depending on high or low index out of bounds, respectively */
func splitSum(of arr: [Int], at: Int) -> (Int, Int) {
    guard at < arr.count else { return (arr.reduce(0, +), 0) }
    guard at >= 0 else { return (0, arr.reduce(0, +)) }

    let lo = arr.prefix(upTo: at).reduce(0, +)
    let hi = arr.suffix(after: at).reduce(0, +)

    return (lo, hi)
}

// example usage
let arr = [Int](repeating: 1, count: 10)
print(splitSum(of: arr, at: 4)) // (4, 5)

Leaving the subject of a non-inclusive suffix method, an alternative approach to your split sum calculation would be to use one of the split(...) methods for Collection types:
func splitSum(of arr: [Int], at: Int) -> (Int, Int) {
    guard at < arr.count else { return (arr.reduce(0, +), 0) }
    guard at >= 0 else { return (0, arr.reduce(0, +)) }

    let sums = arr.enumerated()
        .split (omittingEmptySubsequences: false) { $0.0 == at }
        .map { $0.reduce(0) { $0 + $1.1 } }

    guard let lo = sums.first, let hi = sums.last else { fatalError() }

    return (lo, hi)
}

// example: same as above

I believe the split version is a bit more verbose, however, and also semantically poorer at showing the intent of the code.
Comment: Spectacular.  I have to admit I don't understand **where SubSequence == SubSequence.SubSequence**, nor could I really find it explained in the doco or any tutorials.  Maybe you could generously add a line explaining it, for mortals reading  ;)  Tak!
Comment: @JoeBlow It's not as tricky as one might think at first glance. The return type of the `suffix(after:)` method is `Self.SubSequence`. Now, for some given sequence, say `seq`, the existing `suffix(from:)` method (which we call in the return clause of our method) returns. itself, an instance of type `Self.SubSequence` (where `Self` is the type of `seq`: some type conforming to `Sequence`). So if the `return` statement would look like `return suffix(from: start)`, we wouldn't need the `where SubSequence == SubSequence.SubSequence` specification, since the type of the `return` clause match ...
Comment: ... the return type we've specified in the `suffix(after:)` method, namely, `Self.SubSequence`. In our case, however, we apply the `dropFirst(_:)` method _upon the `Self.SubSequence` instance returned from the `suffix(from:)` call_. The return type of the `dropFirst(_:)` is, also, `Self.SubSequence`, with `Self` being the type of the caller. Since, in our case, the caller is `Self.SubSequence` (with `Self` being the type of `seq`), the _type_ of the chained call `suffix(from: start).dropFirst(1)` is `Self.SubSequence.SubSequence`. Since the return type of the method is `Self.SubSequence`, ...
Comment: ... we need to ascertain that `Self.SubSequence` is indeed the same type as `Self.SubSequence.SubSequence`, hence the specification `where SubSequence == SubSequence.SubSequence` in the "signature" of the extension. So in the end it simply boils down to ascertaining that we return the correct type as specified by the method signature of `suffix(after:)`. Hope this clears things up!
Comment: That will take some thought  :O
Comment: @JoeBlow Glad I could help! That would be my first one, much obliged, likewise thanks!
Comment: your first one, hard to believe.  thanks again!  BTW i'm still slowly digesting your explanation "It's not as tricky as one might think at first glance..."  :-)
Comment: @JoeBlow feel free to post any additional questions regarding it after you feel done digesting it. We'll simply delete our comments in case this comment tail were to grow. And yes maybe that "not as tricky" was not on target :)


Performance Webpack Build.js

Question: Estou iniciando com Webpack. Ele compila todos os arquivos javascript e css em um único arquivo Build.js, Bundle.js, o que seja... No fim ele gera um arquivo totalmente minificado utilizando o comando do Node de Production, mas mesmo assim ele gera um arquivo relativamente pesado. Para um projeto grande ( Que é o meu ), pode chegar a 10mb fácil. Carregar 10mb de uma vez é muito ruim.
Como o Webpack controla isso? No que é vantajoso usar ele se ele me tráz um arquivo minificado porém enorme? Ele seleciona os scripts que serão carregados a partir do import?
var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
          }
        }
      },
      {
      test: /\.css$/,
      include: /node_modules/,
      loaders: ['style-loader', 'css-loader'],
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      },
      {
        test: /\.s(a|c)ss$/,
        loader: 'style-loader!css-loader!sass-loader'
      },
      { test: /\.(png|woff|woff2|eot|ttf|svg)$/,
        loader: 'url-loader?limit=100000'
      }
    ]
  },
  resolve: {
    extensions: ['.json', '.min.css', '.min.js', , '.scss' , '.css', '.js' ],
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map',
  plugins:[
    new webpack.ProvidePlugin({
       $: "jquery",
       jQuery: "jquery"
    })
  ]
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

Obrigado!
Comment: Na verdade ele faz muito mais que isso. Mas você precisa aprender a controlar o que ele está fazendo, o que leva um tempo. Parece o caso de gerar vários "chunks" de JS separados, e não um único build. O webpack é feito para isso, e consegue saber o que está em cada arquivo js gerado e carregá-los aos poucos conforme necessário. Poste sua configuração do webpack na pergunta que melhoram as chances de você conseguir ajuda no seu caso específico.
Comment: Eu pessoalmente acho o webpack complicado, estou usando há um tempo (1 ano, por aí), e tem muita coisa que não sei. Por exemplo, sei que ele faz o que eu disse, mas não sei como fazer no seu código sem reler a documentação. Vamos ver se aparece alguém aqui que saiba responder na lata. Senão em algum momento volto aqui e respondo, porque preciso aprender a fazer isso também :)
Comment: Obrigado pela resposta! Pelo que deu para ver eu ainda sou beeem leigo em Webpack. Eu fiz algumas alterações à mão conforme necessário. Mas básicamente fiz estas configurações a partir de um CLI do VueJS.
Ele no fim me gera um arquivo de umas 20 linhas, mas cada arquivo minificado em apenas uma linha
Comment: Oba. Ele é muito bom né, mas fiquei com um pé atrás com isso. Deve ter algum detalhe que devo estar esquecendo rsrs, de qualquer forma, agradeço a ajuda :)
Comment: será que isso aqui dá uma luz? https://hackernoon.com/optimising-your-application-bundle-size-with-webpack-e85b00bab579 essa pergunta no SO em ingles também parece ir na mesma linha https://stackoverflow.com/questions/31040379/webpack-creating-large-file-with-small-project
Answer: De fato o Webpack oferece alternativas, o Code Splitting usando plugins, e carregamento por demanda usando import da biblioteca SystemJS, a qual retorna uma Promise.
Mas vejo pelo seu código que está tu está usado o Vue.js.
Você pode O Vue.js facilita ainda mais o carregamento por demanda, Veja mais sobre isso:
na própria documentação do Vue.js, e nesse artigo. Há vários artigos na internet sobre isso.
Mais opções:

Se a aplicação está na internet ou você tem certeza 100% que o usuário vai ter conexão com a internet. Use CDN onde for possível.
a) O usuário pode já ter em cache do navegador as mesmas bibliotecas de terceiros que você usa, principalmente bootstrap, jQuery, angular, react...
b) provavelmente o usuário vai baixar o conteúdo de uma biblioteca no servidor CDN do que no servidor de hospedagem e com o mínimo de latência, diminuido tempos de resposta para download de cada arquivo. Servidores CDN são robustos para garantir largura de banda, latência baixa e disponibilidade.
c) Aqui eu recomendo o CDN para bibliotecas de terceiros quase sempre, por causa do item (b). Cabe ao desenvolvedor fazer benchmarks e simular casos de uso, pois pode não haver muita diferença no caso de um site hospedado em bons servidores a curta distância da maioria dos usuários. Spoiler: mesmo com várias requisições HTTP separadas, a latência baixíssima e largura de banda dão vantagem para o CDN.
Comprima seus arquivos Javascript através de uma diretiva de compressão gzip no servidor web (apache, nginx, IIS) ou faça pelo WebPack mesmo com um plugin tipo esse:
https://github.com/webpack-contrib/compression-webpack-plugin
Use uma política de cache ajustada com o seu caso de uso. Bibliotecas de terceiros unidas em um arquivo diferente com maior tempo de expiração de cache. Bibliotecas mais usadas em outro arquivo com menor tempo.
Repense sobre a necessidade de cada uma das bibliotecas, se não vale a pena implementar sua própria função ou extraí-la da biblioteca ao invés de baixar toda a biblioteca por completo.
Comment: Será baixado de uma vez só. O caso é que usando o protocolo HTTP 1, requisições de arquivos são muito custosas. Daí a ideia de unir arquivos. Aí que começa a confusão, tem gente unindo jQuery, angular como arquivos do projeto sendo que teria um ganho muito maior com CDN. O Webpack começa a partir disso mas vai muito além! Você pode unir somente os arquivos de projeto (que não se beneficiariam de um CDN). Você pode usar o Code Splitting, plugins e muitos mais.
Comment: No caso do protocolo HTTP 2, as requisições de arquivos não são custosas pois a conexão com o servidor fica aberta eliminando o custo do round trip de requisição. Você pode carregar arquivo por arquivo com o mesmo (+-) custo final de um só arquivo bundled, com a vantagem de que próximas requisições somente trará arquivos mais novos que o que estão na cache.
Comment: https://developers.google.com/web/fundamentals/performance/http2/?hl=pt-br
Comment: Resposta bem completa!! Mas ainda não matou minha principal pergunta (Ou se matou não ficou muito claro hehe)... O arquivo final, o Bundle.JS de 10Mb, como o navegador trata esses 10Mb de javascript para baixar em uma requisição? Não é melhor fazer várias pequenas requisições? Nesse caso a união que o WebPack faz seria um tanto inútil, não? Obrigado!
Comment: Perfeito cara. Então 1 Bundle enorme daria a mesma perfomance do que várias requisições no HTTP2? Me recomenda algum artigo em relação à isso? Valeu =)
Comment: Perfeito cara, muito obrigado :)

Performance Webpack Build.js


Exclude first row filtering JTable

Question: I got a problem when filtering my JTable. In fact, on my first row I have JComboBoxes in each column. And when I sort which the items of JCombo the first row is also being filtered and disappear.
Here is my Table model:
public static class MyModel extends AbstractTableModel {

    private static final long serialVersionUID = -768739845735375515L;
    private List<Object[]> data;
    private List<String> columnNames;

    public MyModel(List<String> columnNames, List<Object[]> data) {
        super();
        this.columnNames = columnNames;
        this.data = data;
    }

    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.size();
    }

    @Override
    public String getColumnName(int column) {
        return columnNames.get(column);
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return data.get(rowIndex)[columnIndex];
    }

    @Override
    public boolean isCellEditable(int row, int col) { // Pour modifier uniquement la cellule Statut
        if (row == 0) {
            return true;
        } else {
            return false;
        }
    }

    public void setValueAt(Object value, int row, int col) {
        data.get(row)[col] = value;
        fireTableCellUpdated(row, col);
    }

    public void removeRow(int row) {
        data.remove(row);
    }
}

And the combo listener :
private void ComboListener(final JComboBox comboBox){
    comboBox.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    try{
                    String selectedItem = comboBox.getSelectedItem().toString();
                    sorter.setRowFilter(RowFilter.regexFilter(selectedItem));
                    }catch(Exception ex){}
                }
            }
    );
}

Comment: Where's your code that does the table model sorting?
Comment: Are you talking about filtering, rather than sorting? From the looks of your code, you filter based on the contents of the combo box. Then presumably the combo boxes vanish?
Comment: Similar to: http://stackoverflow.com/q/16673437/1438660
Answer: I'm assuming you're talking about filtering, not sorting, based on your current code.
You could make use of the int.. indices argument when creating your filter:
int[] indices = new int[yourModel.getRowCount() -1];
for (int i = 0; i < indices.length; i++) {
  indices[i] = i+1;
}

sorter.setRowFilter(RowFilter.regexFilter(selectedItem, indices));

This will cause your filter to apply to all the rows except row 0.

Exclude first row filtering JTable


Serenity MVC Framework use Web Service

Question: I love the Serenity MVC framework and would like to use it as much as possible. I am returning data from a web service and would like to implement the framework using the return List<>. I know it is built on the Entity Frame work, but is it possible to have an override where we can get the data from a web service rather than a database?
Comment: https://visualstudiogallery.msdn.microsoft.com/559ec6fc-feef-4077-b6d5-5a99408a6681
Comment: What exactly is the *Serenity MVC framework*? I can't find a tag that matches what your after.
Comment: About Serenity MVC: http://serenity.is/
Answer: You should derive your request and response classes from ServiceRequest and ServiceResponse then you can accept any parameter type inside it, e.g:

   MyResponse : ServiceResponse
   {
       Result: List< Something >
   }

Serenity MVC Framework use Web Service


How to print "node title" in comment.html.twig template?

Question: i am styling my comments in comment.html.twig template and need to show "node title" of the node to which the comments belong.
I've tried a number of options, and the only one that works relatively is below:
function enar_preprocess_comment(&$variables){
   $node = \Drupal::request()->attributes->get('node');
   $variables['nodetitle'] = $node->getTitle();
}

However, if I click "reply" in the comments, I get this error.
Error: Call to a member function getTitle() on null in mytheme_preprocess_comment()

My question is, how to print "node title" in comment.html.twig template?
Comment: `$node = $variables['commented_entity'];`
Answer: Because the comment reply page/route does not belong to a Node entity
$node = \Drupal::request()->attributes->get('node');

returns null.
Instead, access the node object with
$node = $variables['commented_entity'];


Differentiate $2\pi x \cos(\pi x^2)$

Question: Can someone please explain to me how to differentiate this equation?
$$2\pi x \cos(\pi x^2)$$
I know you use the chain rule and the product rule but I cannot get the final answer correct.
$$(2 \pi) [-\sin(\pi x^2) 2\pi*x]$$
$$=-4 \pi^2*x* \sin(\pi x^2)$$
Comment: Show the work you've done so far and we can help you find your mistake.
Comment: I edited initial to show my work
Comment: I think you forgot an $x$ somewhere in there.
Answer: I think you forgot an $x$ somewhere. If we use the chain rule,
$$f'(x)=(2 \pi x)(-2 \pi x\sin(\pi x^2))$$
which becomes
$$f'(x)=-4\pi ^2x^2\sin(\pi x^2)$$
not
$$f'(x)=(2\pi)(-2 \pi x\sin(\pi x^2)$$
becoming
$$f'(x)=-4\pi ^2 x \sin(\pi x^2)$$
Comment: Note: my answer is incomplete, because I only analyzed the part of the equation regarding $\sin(\pi x^2)$.
Answer: So,
$\frac{d}{dx}[2\pi x \cos(\pi x^2)]$
The first step I like to do is to pull out constants since $(\alpha f)' = \alpha (f')$
$=2\pi\frac{d}{dx}[x \cos(\pi x^2)]$
Then is product rule with $f=x$ and $g= \cos(\pi x^2)$, you have $(fg)' = f'g + fg'$
$=2\pi(1\cdot\cos(\pi x^2) + x\cdot \frac{d}{dx}[\cos(\pi x^2)])$
Now for the final piece, apply chain rule where $g=\pi x^2$ and $f = \cos(x)$ which states that $[f(g)]' = f'(g)\cdot g'$
$=2\pi(\cos(\pi x^2) + x\cdot (-\sin(\pi x^2))\cdot\frac{d}{dx}[\pi x^2])$
one more derivative to take...
$=2\pi(\cos(\pi x^2) + x\cdot (-\sin(\pi x^2))\cdot(2\pi x))$
finally algebra to simply things
$=2\pi\cos (\pi x^2) - 4\pi^2 x^2\sin(\pi x^2)$
Answer: As you say, you have to use, first, the product rule and, second, the chain rule.
This gives:
$$\frac{d}{dx} 2 \pi x \cos(\pi x^2)=2 \pi \frac{d}{dx}  (x \cdot \cos(\pi x^2)) = 2 \pi \left[ \left( \frac{d}{dx} x \right) \cdot \cos(\pi x^2) + x \left( \frac{d}{dx} \cos(\pi x^2) \right) \right]=2 \pi \left[ \cos(\pi x^2)+x \left(-\sin(\pi x^2)\cdot \frac{d}{dx} (\pi x^2)\right) \right]=2 \pi \left[ \cos(\pi x^2)+x \left(-\sin(\pi x^2) \cdot  (2 \pi x)\right) \right]$$

Differentiate $2\pi x \cos(\pi x^2)$


Flickr module not showing any photos

Question: I am attempting to use the Flickr module 7.x-1.x-dev to display a block of recent photos from a photostream on Flickr. I have setup the API keys and correct user ID, but the block is not producing any output. I've checked the Drupal logs and can't see any issues. I've also run cron and cleared the cache.
Does anyone know how to get this module working or of any alternatives to this module that work in 7? I tried Flickrippr but it produced a lot of PHP errors that brought the site down.
Comment: ((1.)) You chose a `dev` version. Bugs should be expected. ((2.)) This sounds like a bug and should have been reported in the module's issue queue on [drupal.org](https://drupal.org). ((3.)) Asking for module recommendation is considered off-topic on Drupal Answers.
Answer: Use the block Flickr: User photos corresponding with a node's taxonomy term, location and/or date field and under FILTER / SORT ORDER
leave Flickr tags as node taxonomy terms (choose a vocabulary to use) on none.

The sandbox demo at https://simplytest.me/project/flickr/7.x-1.x shows an example in the sidebar. Log in there and check the settings used with your own.

Flickr module not showing any photos


Rollup Accounts - See where pageviews are coming from?

Question: I've set up a rollup account for several off my other domains (Like; mydomain.com, mydomain.org, mydomain.net)
When I look at the rollup account I can see the reports but they all come from "/" instead of "mydomain.org" or "mydomain.net", is it possible to see this somehow? or track it?
Code Im running on the subsites:
<code><script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-xxxxxxxx-1', 'auto');

//roll up account
  ga('create', 'UA-xxxxxxxx-2', {'name':'rollupProperty'});
  ga('send', 'pageview');
  ga('rollupProperty.send','pageview');

</script>
</code>
Answer: I had similar case for one of my clients,
Google Analytics by default shows only page pathe (like /mypage.php instead of mydomain.com/mypage.php, mydomain.org/mypage.php, etc.).
If you want just temporary solution, go to "Behavior -> Site Content -> All Pages" in GA reports and choose "Hostname" as secondary dimension:

If you want always see hostname in your GA reports, then you should create Advanced filter for rollup GA property:

This filter may allow you to extract Hostname(mydomain.org) and Ruquest URI(/mypage.php) and rewrite Request URI by combination "mydomain.org/mypage.php" in GA reports.
Recommend you to test this approach.


Show that ${C_\infty }/\left\langle {{c^n}} \right\rangle \simeq {C_n}$

Question:
Let ${C_\infty } = \left\langle c \right\rangle $ be an infinite
   cyclic group. Show that if $n > 0$, then $${C_\infty }/\left\langle
 {{c^n}} \right\rangle  \simeq {C_n}$$where ${C_n}$ is a finite cyclic
   group with $n$ elements.

My work
Let $f:{C_\infty } \to {C_n}$ is defined by $f({c^k}) = {b^{k\,\bmod \,n}}$, where ${C_n} = \left\langle b \right\rangle {\text{ and }}{c^k} \in {C_\infty }$. We want to show that $f$ - is a homomorphism and $\left\langle {{c^n}} \right\rangle  = {\text{Ker}}(f)$.
Let ${c^k},\,\,{c^l} \in {C_\infty }$, then $f({c^k}{c^l}) = f({c^{k + l}}) = {b^{(k + l)\,\bmod \,n}} = {b^{k\,\bmod \,n}}{b^{l\,\bmod \,n}} = f({c^k})f({c^l})$. Hence, $f$ is a homomorphism.
We claim that $\left\langle {{c^n}} \right\rangle  = {\text{Ker}}(f)$. If ${c^{kn}} \in \left\langle {{c^n}} \right\rangle $, then we have $f({c^{kn}}) = {b^{kn\,\bmod \,n}} = {b^0} = e$.
Conversely, if ${c^a} \in {\text{Ker}}(f) \Rightarrow f({c^a}) = e$. So, ${b^{a\,\bmod \,n}} = {b^0} \Rightarrow a = kn \Rightarrow {c^a} \in \left\langle {{c^n}} \right\rangle $. Clearly, ${\text{Im}}(f) = {C_n}$ and therefore ${C_\infty }/\left\langle {{c^n}} \right\rangle  \simeq {C_n}$.
Comment: Looks like you're trying to use the first isomorphism theorem for groups.  You also need to show that $f$ is surjective.  I'd probably also say $(k+l) \mod n$ instead of $k + l \mod n$ just to make it clear that the mod applies to the sum and not just $l$.  Granted it's clear from context, but still..
Comment: @tilper I used the following fact: "If $f:G \to H$ is a group homomorphism, then $G/{\text{Ker}}(f) \simeq {\text{Im}}(f)$". I don't think i need to show that $f$ is surjective... I showed that $f$ is a homom. then i showed that ${\text{Ker}}(f) = \left\langle {{c^n}} \right\rangle $ and it is clear that ${\text{Im}}(f) = {C_n}$
Comment: Right, I missed the $\text{Im}(f) = C_n$.  That works, as long as you can get away with saying $\text{Im}(f) = C_n$ is clear!
Comment: You haven't specified that $b$ generates $C_n$; it looks like you have chosen an arbitrary element $b\in C_n.$
Comment: @ByronSchmuland right, added this detail.
Answer: The infinite cyclic group is $\Bbb Z$. It has $$\langle c\mid\rangle$$ as a presentation, since it is free.
If we introduce the relator $nc$ for $n\in\Bbb N$, then we get the presentation $$\langle c\mid nc\rangle,\tag{$\mathcal{P}$}$$ which defines $\Bbb Z_n$.$\dagger$
But we get from the presentation of $\Bbb Z$ above to $(\mathcal{P})$ by "killing" $nc $; that is, by quotienting out by the normal subgroup $\langle nc\rangle$, which is where you are. The result then follows from the first isomorphism theorem, by setting the kernel of some homomorpism equal to that normal subgroup.
This is a little cobbled together but I hope it helps :)

$\dagger$ I'm using additive notation here, so $c^n\leftrightsquigarrow nc$.
Comment: Urgh; if you are going to use $\mathbb{Z}$ to represent the infinite cyclic group, then at least have the decency to use additive notation for it, not multiplicative one....
Comment: Is that better, @ArturoMagidin?
Comment: Yes, that is better. It's perverse to both use $\mathbb{Z}$ for the infinite cyclic group *and* use multiplciative notation, given that $\mathbb{Z}$ has a multiplcation... which doesn't turn it into a group, but rather a free monoid of infinite rank with a zero adjoined.


Rspec fails with nested singular route

Question: I have the following routes.rb file (part):
resource :user do
  resources :orders do
    post :verify, :on => :collection
  end
end

My controller spec looks like follows:
require 'spec_helper'

describe OrdersController do
  describe "#verify" do
    it "verifies a recipe" do
      post :verify
    end
  end
end

The spec fails with an ActionController::RoutingError No route matches {:controller=>"orders", :action=>"verify"} even though the route exists and correctly responds in a browser.
Answer: Based on your routes, the describe should look like:
describe Users::OrdersController do
  ...

Answer: Ah, my bad! I've completely forgot that I have the rails-translate-routes gem in place and I don't set a default locale!

Rspec fails with nested singular route


RSYNC and SCP differences

Question: How does rsync differ with scp in terms of transfer speed, maximum transfer size etc ? Or they very similar ? And in what type of scenarios do we need to use these commands ?
Answer: There are two main differences (that I can think of) between rsync and scp.
Before a file is transferred rsync takes the checksums of the file (MD5 and adler-32 I believe) and sends them to the receiver.  After a file is transferred the receiver verifies the data integrity using those checksums. scp does not have such mechanism.  scp uses ssh to transfer the data and although ssh uses checksums on the packet level that's a different story (I believe the default rsync behaviour is also to use ssh for transfers).
Another difference is what happens during a transfer retry.  While scp will ignore any partially transferred set of files and overwrite them on the receiving end, rsync is more clever than that.  Rsync will check the destination for any files present and if their signature matches that of the files on the sender side it will not retransmit these files. It might be possible to overwrite this behaviour but I am not entirely sure.
cheers,
n
Comment: @Bart: You can use the `--no-whole-file` option to force `rsync` to use the delta-transfer algorithm on local-to-local copies.
Comment: @Steven-Thanks for that switch info. It's still something to keep in mind when assuming default behavior, though. That was the part that catches me off guard at times!
Comment: Another difference depends on how you use rsync.  If you use rsync to communicate with a system running an rsync daemon there is no overhead for encryption.  Everything will be sent in the clear.
Comment: I think Rsync sometimes tries to be smarter than it should; if you have a large file...a 200 meg video, for example...and you edit maybe 5 meg of it, rsync will (in a network copy) compare and transfer just that altered 5 meg. BUT if I did it with a mounted share, as in mounting a windows share and doing an rsync from directory A to directory B, rsync will copy the entire 200 meg. I was later told that only if it is transferring over the network will it do the differential copy, which speeds up the transfer job.
Comment: (in other words because I mounted the share in the filesystem, it treats it like a local drive-to-drive or volume-to-volume sync rather than machine-to-networked-machine sync)
Comment: @Bart: Thanks for the info.  I was not aware of this rsync behavior.
Comment: @nayden:  rsync does _not_ start by taking whole-file checksums.
Comment: @Javier: spot on! ;)
Answer: scp(secure copy): copy the files one computer to another (or) local computer.
             ex: scp 10.113.16.1:/source_file  184.108.40.206:/destination_file.
->  but scp is overriting files agin and again.
example:i have files(f1,f2,f3,f4) on source_file directory.again i copy file on
         same destination(scp 10.113.16.1:/source_file
                            220.127.116.11:/destination_file)
destination_file is(f1,f1,f2,f2,f3,f3,f4,f4) overriring.
but rsync is skip the files already copied files.
ex: rsync 10.113.16.1:/source_file  18.104.22.168:/destination_file.(first time)
    o/p:destination_file(f1,f2,f3,f4)
ex: rsync 10.113.16.1:/source_file  184.108.40.206:/destination_file.(second time)
      o/p:destination_file(f1,f2,f3,f4).not override in this command
Comment: More explanation please, it looks like a copypasted logtext.

RSYNC and SCP differences


Starting a OPC UA Server in OpenModelica using OMShell/Linux

Question: I want to run an OpenModelica simulation on an pc running Linux and then connect via opc ua to the simulation. I tried simulating my model in OMShell with simulate(MyTestModel). This worked.
When I add the simulation flags simulate(MyTestModel,simflags ="-rt 1.0 -embeddedServer opc-ua") to start a OPC UA Server OMShell crashes and nothing happens. I tried this in Linux and Windows.
When using OMEdit and setting the flags in the simulation setup it seems to work. However I also have to press the Play Button in the Interactive Plot view to start the simulation. I tested this by connecting to the server with UAExpert.
My question is: Does anybody know why OMShell crashes (doesn't react anymore) when trying to start the OPC UA Server? Or does anybody have any other suggestions on how to achieve my goal of establishing a opc ua connection with an open modelica simulation running on Linux?
Thanks!
My test model is:
model MyTestModel
  input Real x;
  Real y;
equation
  y = x;
end MyTestModel;

Answer: As always I have already tried to find the solution for several days but after posting the question I found the solution myself. I have to start the simulation via the OPC UA interface after starting the server. I changed the node "Run" to true and the simulation of my model started. This is probably the same as pressing the play button in OMEdit (as described above).
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: To provide a few more details: The qualified name is `1:OpenModelica.run` (where `1` is the namespace). Additional options to control the (interactive) simulation are: `1:OpenModelica.step` (when set to `true`, the simulator takes a single step), `1:OpenModelica.realTimeScalingFactor` (the real-time scaling factor; 1.0=real-time, 0.0=disabled), and `1:OpenModelica.enableStopTime` (enabled when using the `stopTime` to stop the simulation).


How to solve$(2xy^2-3y^3)dx+(7-3xy^2)dy=0$.

Question: How can we solve the following differential equation?
$$(2xy^2-3y^3)dx+(7-3xy^2)dy=0.$$
I solved it by using change of variable $y=z^\alpha$ but I'm looking for other ways to solve it.
Comment: You want to prove??? Maybe to solve? I am confused.
Answer: You dont need to look for an integrating factor since if you rewrite (by dividing both sides with $y^2$) the equation as $(2x-3y)dx+(7y^{-2}-3x)dy=0$, then your equation becomes exact one. Also, actually this means that $y^{-2}$ is the integrating factor.:)


Why does Visual Studio check out the .vspscc file when I add a file to a project?

Question: If I add a new file to a project under TFS source control, it will check out the project file and the corresponding .vspscc file for that project file.
The project file itself changes (to include the new file), but the .vspscc file doesn't change at all. Why bother checking it out? Is there a way to disable it from being checked out and if there is, should I?
Comment: It's a very good question. When adding projects to the Source Control it seems to create **and version** the .vspscc files. If you however try to export and re-add the project to another source control, the source control wizard puts these files to the ignored list. Sadly this question has not been answered with a definite **yes because...** or **no because...** answer.
Answer: It gets checked out because under certain conditions it will be modified..and thus they checked it out as a matter of default.  I wouldn't worry about it..it's not hurting anything, and if you disable it, it might bite you badly in the future in a bizarre way.
Comment: Here's an answer: Team Foundation uses these to store lists of files that have been excluded from source control.  We leveraged some of the existing SCC integration layer in Visual Studio to integrate Team Foundation, and these files were one of the carryovers.  http://social.msdn.microsoft.com/Forums/en/tfsgeneral/thread/9920911d-1a7e-4ada-90cd-b1b910586cf4
Comment: thanks. just out of curiosity, any idea what those certain conditions are?
Comment: Not a clue.  I've just see it checked in with a different size once in a blue moon, so i assume it's being changed occassionally.  When i get to work monday, i can see if i can tell what's different
Comment: i just looked at the version history on a vspscc file with 9 months of history and there's dozens of checkins with no changes since the first time it was added.
Comment: I could very well be wrong, as i can't verify (since i'm at home and not work), but my mind tells me i've seen it's size change.  (could just be hallucinating as well :-S)  Regardless, it won't hurt anything to have it checked out each time
Comment: Unfortunately, in my case I have latency between me and the TFS servers and there are about 87 of these in the solution.  Each checkout takes 15 seconds or so, during which time I can't do anything productive.  So in my case "not worrying about it" is not an option.
Comment: I found no issues excluding these types of files from TFS. Unless I'm missing something?
Comment: The bizarre bite can happen because even MSFT doesnt know what these files are for.  I've excluded them for years, and the only problem i have is that nuget tries to check one out before checking if it exists.
Answer: According to this post of Ben Ryan:

Team Foundation uses these to store lists of files that have been excluded from source control.  We leveraged some of the existing SCC integration layer in Visual Studio to integrate Team Foundation, and these files were one of the carryovers.  I'll have to check into what the logic was in breaking out these SCC settings into separate files as opposed to putting them in the solution and project files' SCC sections.
Answer: This file is a holdover from past VSS/TFS implementations, like Paulo Santos posted.
On the solution level, I have found no functional use for these files. In 10 years of using TFS, I have never seen that file altered. You can delete these .VSSCC files, as I commonly do for my closed source solutions.
But if you delete the solution-level .vsscc file, you will get a non-destructive error message on the first time open of the solution file...only after a new branch is created. All subsequent solution opening will not show the error message again.
My TFS setup standards have the solution file alone in the root folder, all projects are under sub-folders. Since those .vsscc files double the number of files in my root, I always delete them.
On a project level, I leave those files, as my team never opens project files directly, only solution .SLN files.
For my team, I prefer programmer ease of opening solutions over that one-time error message.
Comment: Unfortunately, it appears that even if you delete the files, Visual Studio (even 2015) will re-generate them.


Wordpress shows permanent loop redirect after upgrading from Apache 2.2 to Apache 2.4

Question: I've upgraded my Apache 2.2 web server to 2.4 today and then some Wordpress installations started to get infinite loops from non-www to www and from www to non-www :(
Removing .htaccesss didn't helped.
How to solve this ? Example domain config:

SetEnvIf X-Forwarded-Proto https HTTPS=1

ServerAdmin firstname.lastname@example.com

ServerName internet.az.pl

ServerAlias www.internet.az.pl

DocumentRoot "/home/admin2/komputery"

DirectoryIndex index.php index.html index.shtml index.htm index.pl index.py index.cgi index.rb default.htm Default.aspx Default.asp

ScriptAlias /cgi-bin/ "/home/admin2/internet.az.pl/cgi-bin/"

<IfModule mod_fastcgi.c>
        Alias /internet.az.pl.0fake "/home/admin2/komputery/internet.az.pl.0fake"
        #FastCGIExternalServer "/home/admin2/komputery/internet.az.pl.0fake" -host 127.0.0.1:52474 -idle-timeout 300 -pass-header Authorization
        FastCGIExternalServer "/home/admin2/komputery/internet.az.pl.0fake" -socket /opt/configs/php-fpm/sock/admin2.sock -idle-timeout 300 -pass-header Authorization
        AddType application/x-httpd-fastphp .php
        Action application/x-httpd-fastphp /internet.az.pl.0fake
        <Files "internet.az.pl.0fake">
                RewriteCond %{REQUEST_URI} !internet.az.pl.0fake
        </Files>
</IfModule>

<Directory "/home/admin2/komputery/">
        AllowOverride All
        <IfVersion < 2.4>
                Order allow,deny
                Allow from all
        </IfVersion>
        <IfVersion >= 2.4>
                Require all granted
        </IfVersion>
        Options +ExecCGI
        <FilesMatch \.(cgi|pl)$>
                SetHandler cgi-script
        </FilesMatch>
</Directory>

<IfModule mod_php5.c>
        php_admin_value sendmail_path "/usr/sbin/sendmail -t -i"
        php_admin_value sendmail_from "internet.az.pl"
        Include /home/kloxo/client/admin2/prefork.inc
</IfModule>

<Location "/">
        Allow from all
        Options -Indexes -FollowSymlinks +SymLinksIfOwnerMatch

        <IfModule mod_php5.c>
                php_admin_value open_basedir "/home/admin2:/tmp:/usr/share/pear:/var/lib/php/session/:/home/kloxo/httpd/script:/home/kloxo/httpd/disable/:/usr/bin"
        </IfModule>
</Location>

CustomLog "/home/httpd/internet.az.pl/stats/internet.az.pl-custom_log" combined
ErrorLog "/home/httpd/internet.az.pl/stats/internet.az.pl-error_log"

and also httpd.conf:
   ServerTokens Prod

ServerRoot "/etc/httpd"

# MR -- must be disable here because can not overrite! -- importance for proxy-to-apache
# Listen 80

Include conf.modules.d/*.conf

User apache
Group apache

ServerAdmin root@localhost

<Directory />
    AllowOverride none
    Require all denied
</Directory>

DocumentRoot "/var/www/html"

<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>

# Further relax access to the default document root:
<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

<Files ".ht*">
    Require all denied
</Files>

ErrorLog "logs/error_log"

LogLevel error

<IfModule log_config_module>
        ## MR -- change %h to %a to fix mod_remoteip issue
    LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%a %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    # Alias /webpath /full/filesystem/path
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
</IfModule>

<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    TypesConfig /etc/mime.types

    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #AddHandler cgi-script .cgi
    #AddHandler type-map var

    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    MIMEMagicFile conf/magic
</IfModule>

Alias /error/ "/home/kloxo/httpd/error/"

<IfModule mod_negotiation.c>
    <IfModule mod_include.c>
        <Directory "/home/kloxo/httpd/error/">
            AllowOverride None
            Options IncludesNoExec
            AddOutputFilter Includes html
            AddHandler type-map var
            <IfVersion < 2.4>
                Order allow,deny
                Allow from all
            </IfVersion>
            <IfVersion >= 2.4>
                Require all granted
            </IfVersion>
                LanguagePriority en es de fr
            ForceLanguagePriority Prefer Fallback
        </Directory>

        #ErrorDocument 500 "The server made a boo boo."
        #ErrorDocument 404 /missing.html
        #ErrorDocument 404 "/cgi-bin/missing_handler.pl"
        #ErrorDocument 402 http://www.example.com/subscription_info.html

        ErrorDocument 401 /error/401.html
        ErrorDocument 403 /error/403.html
        ErrorDocument 404 /error/404.html
        ErrorDocument 500 /error/500.html
        ErrorDocument 501 /error/501.html
        ErrorDocument 503 /error/503.html
        ErrorDocument 504 /error/504.html
    </IfModule>
</IfModule>

EnableSendfile on

IncludeOptional conf.d/*.conf

Answer: First... stop using IfModule on bits that aren't optional.  (not sure what is or is not required)  They're only useful if you have a fall-back way of recovering if that module doesn't exist or isn't loaded.  Otherwise, apache will start without error... despite the fact that 90% of your config won't actually be loaded.
A quick way to test and ultimately fix... is to remove all of the IfModule statements... and then restart apache.  You'll almost certainly get errors.  Read the error logs.  Look at what errors you get... (i.e. can't load blah blah) and enable/install/rebuild the necessary modules that are required to make your site work.
Comment: It's a part of larger config for many options like mod_ruid2, mod_suphp etc.
Comment: That's fine.  That doesn't invalidate my answer.  If it's not optional... you should error rather than permit apache to load.  IfModule silences those errors... which is bad.
Comment: OK. Does it matter if I use nginx as reverse proxy before apache ? It was working well before upgrade to apache 2.4.
Comment: It shouldn't make any difference.  As long as your nginix server is behaving properly... it won't affect Apache.  (and vise-versa)
Comment: I just found all my .htaccess redirections from www to non-www also does not work, but no redirect loop.
Comment: is mod_rewrite installed/enabled?
Comment: Yes it is. All is working, but no redirections ;(
Comment: It ended restoring Apache 2.2 ;(
Answer: The problem was in nginx - changing line:
proxy_set_header X-Host $var_domain;

to
proxy_set_header X-Host $host;

fixed the problem
Comment: Can you mark your answer as valid ?


Run time complexity of nearest neighbor

Question: A paper titled, "Efficient Neighbor Searching in Nonlinear Time Series Analysis (1996)" download link mentions that the time complexity for the naive NN approach is $N^2/2$ i.e., $O(N^2/2)$ where $N$ denotes the number of datapoints. I have attached a screenshot from the paper where this complexity is mentioned (second paragraph). However, in textbooks it is mentioned that the complexity of $O(N)$. I am a bit confused. Can somebody please help, what is the correct answer and why $O(N^2/2)$ is mentioned in the paper.
Answer: The paper mentions that the time complexity for the naive NN approach is $^2/2$ in order to argue for using non-naive algorithms that are faster for large $N$.
In fact, the paper goes on to say that $O(N\log N)$ is possible for arbitrary data distributions, using $k$-d trees and their variants and that $O(N)$ is possible for some data distributions.
My impression is that interest now is more in the dependence on dimension rather than on $N$.
Comment: Thank you for your answer....by naive NN do you mean the k nearest neighbor given here: https://sebastianraschka.com/pdf/lecture-notes/stat479fs18/02_knn_notes.pdf  Can you please clarify this point?
Comment: I mean the algorithm where you compute all $N\choose 2$ distances between pairs of   points and pick the smallest ones.

Run time complexity of nearest neighbor


How can I keep track of nginx restarts and reloads?

Question: I have an nginx reverse-proxy on a ubuntu server in AWS. How can I see when it's configurations were reloaded, either via CLI or otherwise, and when it was restarted altogether?
If it doesn't record these events on its own, how can I log them indirectly through a script of some kind?
Comment: Is your `nginx` server running as a `systemd` service?
Comment: If your nginx has a lua module enabled then you could use `init_by_lua_block` to write to log file on config reload/restart.
Comment: @Uberhumus yes it is
Comment: @AlexeyTen ok I will research this approach further
Answer: With some auditd rules
<code>-a always,exit -F path=/usr/sbin/nginx -k nginx_exec
-a always,exit -F arch=b64 -S kill -F a0=1 -F a1=9 -k nginx_restart
-a always,exit -F arch=b64 -S kill -F a0=1 -F a1=1 -k nginx_reload
</code>
You can then check with
<code>ausearch -k nginx_exec
ausearch -k nginx_restart
ausearch -k nginx_reload
</code>


ANOVA or t-test and multiple testing

Question: I have 7 groups, one healthy group and 6 treatment groups and 5 traits. I would like to test for each trait if there are any significant difference between each treatment group and healthy group.
Would it be more appropriate to perform a T-test for each trait or ANOVA?
In case T-test is the answer, should I consider adjustment for 6x5=30 tests (i.e. 0.05/30)?
Answer: The usual approach is to perform ANOVA and, if ANOVA shows significant differences, perform group comparisons making adjustments for multiple comparisons.
The adjustment you propose would be Bonferroni correction which is widely used (because it's simple) but rather conservative. You might be interested in some alternatives.
Comment: The only virtue of Bonferroni is it is simple. The problem is not it is conservative, but that it is ridiculously conservative. Much, much,better to use Dunnett, FDR, or some of the cool tools in the `multcomp`.
Comment: I don't see any value in doing the ANOVA. If all treatment effects are very similar then the power of ANOVA will be low.
Answer: There is no need to do an ANOVA first if your method for comparing means controls the Type I error rate adequately. For the problem of comparing multiple groups with a control, I would recommend Dunnett's test. Because you have multiple traits, the Dunnett test results should be corrected for the number of traits with the Bonferroni adjustment.
Comment: Isn't a problem with doing Bonferroni after Dunnett that the traits are likely correlated, but Bonferroni does poorly with correlated tests? Something like the false discovery rate correction would be my pick either after doing Dunnett, or, on all the p-values.
Comment: Bonferroni is conservative with correlated tests so does control the Type I error rate although it can have low power. FDR correction is a good alternative.
Answer: Doing multiple t-tests increase the error (type I). It is better to do first an ANOVA and if there is a significant difference, then you can do a dunnett test (dedicated for comparison between a control group and other groups) or a Tukey test (multiple comparison).

ANOVA or t-test and multiple testing


Rolex Paris Masters 2018: Federer haven't decided

Question: This is something that really confuses me. Federer obviously still haven't decided whether or not he's gonna participate in Paris Masters. Now, how can this be, since all the other players already started? Djokovic, for instance, came to round of 16, and Federer still doesn't know whether he's gonna play?
Does it have anything to do with previous tournament score for a given player? Ie. higher ranked players don't need to start playing before the round of 8, for instance, so that gives them more time to decide whether or not to participate? If this is the
Comment: If you look at the [draw of the Paris Masters](https://en.wikipedia.org/wiki/2018_Rolex_Paris_Masters_%E2%80%93_Singles#Section_3), you can see that all 16 seeded players received [bye](https://en.wikipedia.org/wiki/Bye_(sports)) into the second round. At the moment, only Cilic and Djokovic already played their first match (which is in the 2nd round). I do not know what exactly are the limits until when a player can withdraw, but in this tournament one of the seeds has already done that - Kyle Edmund withdrew from the tournament and was replaced by Matthew Ebden.
Comment: Please, if you dislike the question, explain why is it poorly written. Help to ask better questions.
Comment: @Martin thanks. Please post this as an actual answer.
Answer: From @Martin in comments:

If you look at the draw of the Paris Masters, you can see that
  all 16 seeded players received bye into the second round. At the
  moment, only Cilic and Djokovic already played their first match
  (which is in the 2nd round). I do not know what exactly are the limits
  until when a player can withdraw, but in this tournament one of the
  seeds has already done that - Kyle Edmund withdrew from the tournament
  and was replaced by Matthew Ebden


Dúvida em relação ao protocolo https

Question: Estou configurando um servidor Apache em Debian.
Ao acessar https://.../index.php pelo Chrome , tenho o seguinte resultado:

Então minhas dúvidas são:

Para aparecer :

Eu preciso necessariamente de um certificado pago, ou existe outro caminho?

Para não aparecer o alerta do browser, um caminho seria redirecionar
o https para o http, é possível isso no Apache?
Comment: Eu não entendo do assunto, mas acho que não precisa necessariamente ser um certificado pago. Só precisa ser um certificado que o chrome reconheça como confiável.
Comment: Aperte F12 e dê uma olhada no Console, pode ser falta de certificado como também pode ser algum resource em HTTP e não HTTPS inserido no corpo da página.
Comment: Até onde sei, é possível obter certificados reconhecidos free através do https://letsencrypt.org.
Comment: @LINQ não basta ter um certificado, tem que ser um certificado dado por uma autoridade reconhecida pelo Google para o caso do Chrome.
Comment: Isso mesmo que eu quis dizer, @Renan.
Answer: Cada navegador diferente possui uma lista dos certificados em que confia. Em geral, todos os certificados pagos são considerados confiáveis pelos principais navegadores. Já para os certificados gratuitos, você terá variações.
O mais conhecido dos certificadores gratuitos deve ser o Let's Encrypt. Eles têm uma página na qual listam quais navegadores confiam em seu certificado.
Note que a maioria dos navegadores e outros softwares confia neles. Apenas poucos players grandes no mercado não têm confiança (como o Windows Live Mail).
Já para mudar o protocolo de acesso à sua página, é sim possível fazer, de forma bem simples. Não sou especialista em Apache mas se com .htaccess ou similar você puder fazer um redirecionamento server-side, isso já é suficiente. Note apenas que, sem https, todo o tráfego ao seu site pode ser lido por intermediários.
Answer: Você pode colocar um certificado gratuito, conheça:
Let's Encrypt is a free, automated, and open Certificate Authority
Instalar
Install Let's Encrypt to Create SSL Certificates
Configurar para o Apache
SSL Certificates with Apache on Debian & Ubuntu
Redirecionamento HTTPS para HTTP (.htaccess)

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

Comment: Creio que se tem um tempo para instalar e configurar um certificado é melhor do que usar o redirecionamento de https para http.

Dúvida em relação ao protocolo https


ABC. How can it avoid the likelihood function?

Question: According to the Wikipedia article, we have the scenario shown below, but how can ABC generate simulation datasets from samples of $\theta$ without knowing or evaluating the likelihood function?
For example, how would this method work for a normal $N(\mu, \sigma)$ distribution? Assuming that the parameter to estimate is $\mu$ and that $\sigma$ is known, how would it generate the simulations without evaluating $N(\mu, \sigma)$?
Answer: Approximate Bayesian Computation (ABC) is useful when you can simulate data, but cannot evaluate the likelihood function analytically. You seem to assume that it is necessary to know the likelihood function  $l(\theta) = P[D|\theta]$ to simulate data. I'm not sure how you came to that conclusion, but there are ways to simulate data that do not involve the likelihood. ABC does not 'provide' you with such a way of simulating data. You have to come up with some suitable simulation approach yourself.
In your example, one would draw values for $\mu$ from the prior distribution $p(\theta)$, and simulate a sample $\tilde D$ from an $N(\mu, \sigma)$ distribution. We can use a quantile-transformation $\Phi^{-1}(u)$ of a uniform distributed random number $u$ here. This requires that we know the quantile-function $\Phi^{-1}$ of $N(\mu, \sigma)$, but not the likelihood function $P[D|\theta]$. Alternative, we could even do a real world experiment which is known to produce $N(\mu,\sigma)$ disturbed measurements.
The idea of ABC now is, that if $\tilde D$ is identical to the real data $D$, then $\theta$ also is a sample from the posterior distribution $p(\theta|D)$. If we get enough of such samples, we can use the then to approximate the posterior distribution itself. As we normally would hardly ever observe a simulation with produces exactly $D$, we allow for a small mismatch $\epsilon$ between $D$ and $\tilde D$, which introduces another approximation.


sprite goes thourgh my platform and gets stuck (pygame)

Question: When I try and jump on a platform, I clip through it. I have tried everything and my project is due on monday. Also this is my first stackoverflow question and I just recently started learning pygame and python. Thanks in advance
import pygame
import sys
import time
pygame.init()
screenSize = (800,600)
displayScreen = pygame.display.set_mode((screenSize),0)
pygame.display.set_caption("U1A2 Test")

WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)

displayScreen.fill(WHITE)
pygame.display.update()
clock = pygame.time.Clock()
fps= 60
game = False
menu = True
inst = False
jump= False
x = 53
y = 552
m = 0
n = 0
dx = 0
dy = 0
sprite= pygame.image.load('block sprite.png')
#PlayerRect = pygame.rect(x,y,sprite.get_width(), sprite.get_height())
walls = []
level1 = [

    "WWWWWWWWWWWWWWWWWWWWWWWWWW",
    "                         ",
    "                         ",
    "                         ",
    "                         ",
    "                         ",
    "  WW                     ",
    "                         ",
    "                         ",
    "     WW                  ",
    "          WWWW           ",
    "                         ",
    "                WWW      ",
    "                         ",
    "                         ",
    "         WWW             ",
    "   WWW                   ",
    "                         ",
    "WWWWWWWWWWWWWWWWWWWWWWWWWW",
    ]

for row in level1:
    for col in row:
        if col == " ":
            jump = False
        if col == "W":
            wallRect = pygame.Rect(m,n,32,32)
            walls.append(wallRect)
            jump = True
        m += 32
    n += 32
    m = 0

while menu:

        fontTitle = pygame.font.SysFont("Ariel", 72)
        textTitle = fontTitle.render("change this", True, (255,0,0))
        displayScreen.blit(textTitle,(35, 50))

        fontTitle = pygame.font.SysFont("Ariel", 52)
        textTitle = fontTitle.render("Press 1 to play", True, (255,0,0))
        displayScreen.blit(textTitle,(35, 100))

        fontTitle = pygame.font.SysFont("Ariel", 52)
        textTitle = fontTitle.render("Press 2 for instructions", True, (255,0,0))
        displayScreen.blit(textTitle,(35, 150))
        pygame.display.update()

        fontTitle = pygame.font.SysFont("Ariel", 52)
        textTitle = fontTitle.render("Press 3 to quit", True, (255,0,0))
        displayScreen.blit(textTitle,(35, 200))
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_1:
                    print "ds"
                    game = True

                elif event.key == pygame.K_2:
                    menu = False
                    inst = True
                    displayScreen.fill(WHITE)
                elif event.key == pygame.K_3:
                    menu = False

        while game:

            #pygame.draw.rect(displayScreen,GREEN,PlayerRect,0)
            PlayerRect = pygame.Rect(x,y, sprite.get_width(), sprite.get_height())
            displayScreen.blit(sprite,(x,y))
            pygame.display.flip()

            #pygame.draw.rect(displayScreen, (255, 0, 0), PlayerRect, 1)

            clock.tick(fps)
            for event in pygame.event.get():
                if event.type ==pygame.QUIT:
                    pygame.display.quit()
                    sys.exit()

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_a:
                        dx = -7

                        displayScreen.fill(WHITE)

                    elif event.key == pygame.K_d:
                        dx = 7
                        displayScreen.fill(WHITE)

                    elif event.key == pygame.K_w:
                        dy = -25

                    elif event.key == pygame.K_s:
                        dy = 25
                        displayScreen.fill(WHITE)

                    elif event.key == pygame.K_q:
                        stop = True
                        displayScreen.fill(WHITE)

                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_a or event.key == pygame.K_d:
                            dx = 0
                    elif event.key == pygame.K_w or event.key == pygame.K_s:
                            dy = 0

            oldx = x
            oldy = y
            x = x + dx
            y = y + dy

            if game == True:
                dy = dy + 2

            if (x>=795 or x<=33):
                x=oldx

            if (y<=5 or y>=550):
                y=oldy
            displayScreen.fill(WHITE)

            for wall in walls:
                if PlayerRect.colliderect(wall):
                    if dx > 0:
                        PlayerRect.left = wall.right

                    if dx < 0:
                        PlayerRect.right = wall.left

                    if dy > 0:
                        PlayerRect.bottom = wall.top

                    if dy < 0:
                        PlayerRect.top = wall.bottom

                    dy = 0

            for wall in walls:
                pygame.draw.rect(displayScreen,BLUE,wall,0)
                #pygame.draw.rect(displayScreen, (255, 0, 0), wall, 1)

            time.sleep(0.01)
            pygame.display.update()

        while inst:
                fontTitle = pygame.font.SysFont("Ariel", 72)
                textTitle = fontTitle.render("Instructions", True, (255,0,0))
                displayScreen.blit(textTitle,(35, 50))

                fontTitle = pygame.font.SysFont("Ariel", 52)
                textTitle = fontTitle.render("- Use W to jump,S to fall", True, (255,0,0))
                displayScreen.blit(textTitle,(35, 100))

                fontTitle = pygame.font.SysFont("Ariel", 52)
                textTitle = fontTitle.render("- Control your jump by using the A and D keys", True, (255,0,0))
                displayScreen.blit(textTitle,(35,150))
                pygame.display.update()

                fontTitle = pygame.font.SysFont("Ariel", 52)
                textTitle = fontTitle.render("- Move left and right with the A and D keys", True, (255,0,0))
                displayScreen.blit(textTitle,(35, 200))
                pygame.display.update()

                fontTitle = pygame.font.SysFont("Ariel", 52)
                textTitle = fontTitle.render("Press 3 to exit", True, (255,0,0))
                displayScreen.blit(textTitle,(35, 250))
                pygame.display.update()

                for event in pygame.event.get():
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_3:
                            inst = False
                            displayScreen.fill(WHITE)
                            menu = True

pygame.quit()
sys.exit()

Comment: `"I have tried everything."` I doubt it. Please create a [mcve] instead of dumping a wall of code in a question and saying "Fix this." Questions seeking debugging help (**"why isn't this code working?"**) must include the desired behavior, *a specific problem or error* and *the shortest code necessary* to reproduce it **in the question itself**. Please also detail what you have tried, what sort of debugging you have attempted, and what the results were. Also, you mis-spelled the font name. It's `Arial`. Finally, it would be helpful if you uploaded `block sprite.png`.
Answer: Your collision resolution code doesn't work the way you intend because it modifies PlayerRect rather than x and y. PlayerRect gets recreated at the start of each pass through the main loop, so the changes from the collision don't persist. You need to modify x and y in the collision code or change how PlayerRect is setup and used so that changing it persists between frames.
Comment: where am i recreating the PlayerRect?
Comment: You do `PlayerRect = pygame.Rect(x,y, sprite.get_width(), sprite.get_height())` every cycle of the `while game` loop.


Dynamically render a bootstrap element in a template

Question: I want to dynamically render a bootstrap icon in my template based on the result of a function.
I tried something like this
           <template>

                    {{ getUsersEmaillRequestStatus(user.id) === EMAIL_STATUS.SUCCESS ?
                     `<b-icon icon="check-circle"></b-icon>`
                      : "something else" }}

            </template>

And it just renders everything inside my double curly's.
I also tried to do something like this

emailResultFunction() {

     return `<b-icon icon="check-circle" style="color: #328dd1" font-scale="4"></b-icon>`
}

and it just doesn't work either. How do can I render an icon dynamically based on the result of a function?
I also tried to use just and svg and i couldn't get that to work either.
Answer: Use v-if on the  to conditionally render that component:
<template>

Something else...

</template>

demo
Comment: lol, woof. of course. This is how you know you've been coding for too long and need to take a break. thank you for the answer.


Which one should be to cross validated?

Question: I felt a little bit puzzled about cross-validation.  CV is a method to find the best parameter to check the generalization ability of the classifier in the classification problem.

I am really not sure whether I should apply cross-validation on the training set or on the entire dataset? I prefer on the training set because if you apply it to the entire set, it will lead to overfitting again.
Next question is: what is the correct step to use cross-validation in the classification problem. My view is (1)separate the data set as training set and testing set;(2)apply CV to the training set to get the best parameter; (3)use the best parameter to train a model;(4)use this model to test the testing set.

Am I correct?
Comment: I have found a slide about SVM and libSVM in Python from Chaoyang University of Technology, which makes me more clear on this question. You can also check it from [http://web.csie.cyut.edu.tw/~shwu/PR_slide/SVM.pdf](http://web.csie.cyut.edu.tw/~shwu/PR_slide/SVM.pdf) THX~
Answer: CV as a method to find the best hyperparameter should be done on the training set, as you indicated.
CV as a method of evaluating a modeling process should be done on the whole set, however.

Which one should be to cross validated?


Why are two bronze medals awarded in judo at the Olympics?

Question: As you can see in the below for judo competitions, the losers of both semi-finals both receive the medal.

This is notably unusual for an Olympic competition. Why do both contestants get the same medal?
Comment: To complement your screenshot, I will add link to the Wikipedia article [Judo at the 2016 Summer Olympics](https://en.wikipedia.org/wiki/Judo_at_the_2016_Summer_Olympics). (I guess Wikipedia links can be considered relatively stable.)
Answer: This is fairly common for sports with knockout rounds, as the required "3rd/4th place" playoff match always feel a bit pointless - see for example boxing or taekwondo (links to 2012 rather than 2016 just because the 2016 hasn't yet reached the medal rounds in those sports). For a non-Olympic example of the same, see Euro 2016 where again there is no 3rd/4th place playoff.
For combat sports, this is even more common; imagine a boxer who was knocked out in the semi-finals: encouraging them to stand up again to fight in a 3rd/4th place bout would be medically incredibly irresponsible. This is probably less of an issue in judo than the striking combat sports, but still a consideration.
Comment: No, absolutely not. They just don't have a 3rd/4th place match.
Comment: do you mean they make the 3rd/4th place to be like a friendly match?
Comment: @PhilipKendall I think you are confused with boxing which has no 3rd/4th place match.
Answer: It is not an easy question to answer, but let me try to simplify the answer. In order to understand why some sports give two bronze medals instead of one, you have to understand what 'repechage' is. According to the linked Wikipedia article:

Repechage (/rəpɛʃˈɑːʒ/; French: repêchage, "fishing out, rescuing") is
  a practice in series competitions that allows participants who failed
  to meet qualifying standards by a small margin to continue to the next
  round.
Martial arts
In karate, judo, taekwondo, and wrestling
  tournaments, single-elimination brackets are used to determine the two
  athletes who will compete in the final for first and second place. The
  repechage bracket is built from athletes who were knocked out by the
  finalists and building brackets to determine third place. Repechage
  addresses the possibility of two top competitors meeting in an early
  round, allowing the loser a chance to compete for a bronze medal.
  Repechage was formerly widely used in fencing tournaments, but the
  majority have now abandoned it, an exception being United States
  Fencing Association Division I tournaments. (emphasis mine)

It takes a very short time to determine a winner in those sports mentioned above and they are intense and require a lot of stamina. Even if you are ranked No. 3 in the world, if you meet a high-ranked opponent in a relatively early stage, you may not be able to get any medal. That's why there is repechage to give one more chance to those who were knocked out by the finalists at earlier tournaments.
One thing that is very important to note is the rules of a sport are governed by the sport's governing body. Those rules have nothing to do with the rules of the Olympics. That's why a few sports have the repechage system while a majority don't. All the rules in sports boil down to the same opportunity and fairness and if a governing body of a sport deems it fair and reasonable to give two bronze medals to those who deserve them, they can decide so.


Prove $\prod\limits_{d|n}d =n^{\frac{d(n)}{2}}$

Question: Prove $\prod\limits_{d|n}d =n^{\frac{d(n)}{2}}$
First, I am confused by the notation in this problem and understanding what it is I am actually trying to prove. Also, I do not know where to begin proving this problem
Comment: $d\mid n$ means $d$ is a divisor of $n$, so $\prod\limits_{d\mid n}d$ is the product of all divisors of $n$. For $n = 6$ for example, $1\cdot 2\cdot 3 \cdot 6 = 36$. $d(n)$ is the number of divisors of $n$.
Comment: Hint: Each divisor as an equal and opposite divisor :)
Answer: Let $S(n) = \prod_{d \vert n} d \tag{$\star$}$ Note that if $d \vert n$, then so does $\dfrac{n}d$. Hence, we also have that $S(n) = \prod_{d \vert n} \dfrac{n}d \tag{$\dagger$}$ Multiplying $\star$ and $\dagger$, we get that
$$S(n)^2 = \prod_{d \vert n}d \prod_{d \vert n} \dfrac{n}d = \prod_{d \vert n}\left(d \cdot \dfrac{n}d \right) = \prod_{d \vert n} n = n^{d(n)}$$
From this, we get that
$$S(n) = n^{d(n)/2}$$
Answer: The $\Pi$ notation means product. With the subscript $d \mid n$, it's saying "multiply all divisors of n". The $d(n)$ function in the exponent refers to the divisor function. You can probably take it from there.
Hope this helps!


Safely returning float value in threads

Question: i wish to make a thread return a float value.
Changing the data type from float to long works fine, but not with float.
Any help? Thanks.
void * funcFloat(void * arg){
    float x = *(float *)arg;
    printf("Received: %f\n", x);
    return (void *)x;
}

Answer: Try
void * funcFloat(void * arg){
   return arg;
}

Or
 void * funcFloat(void * arg){

     float * f = malloc(sizeof(f));
     *f = 1.2345667f;
     return f;
 }

Then get the owner of the return value to tidy up
Comment: Using
pthread_join(tf, (void *)&z);
does not seem to work, any suggestion?
Comment: What is `z`? Apart from a character in pulp fiction!
Comment: In main, i declared z as float. I wish to save the value returned by the thread in this variable.
Answer: As the other answer indicates, your original problem is that you're returning the float itself (x) when you should be returning a pointer to it.
As for your comment about getting the return value with pthread_join(), note its prototype:
int pthread_join(pthread_t thread, void **retval);

It takes a pointer to a void * in the second argument, which is why calling pthread_join(tf, (void *)&z); where z is a float does not work. Here's a working example, minus error checking:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void * funcFloat(void * arg){
    float x = *(float *)arg;
    printf("Received: %f\n", x);
    float *returnf = malloc(sizeof(returnf));
    *returnf = x;
    return returnf;
}

main(int argc, char **argv) {
    pthread_t thread;
    float f = 3.14159;
    float f2;
    float *joinedf = NULL;

    pthread_create(&thread, NULL, funcFloat, &f);
    pthread_join(thread, (void **)&joinedf);
    f2 = *joinedf;
    free(joinedf);

    printf("final: %f\n", f2);
}

Safely returning float value in threads


Intervalo de datas C#

Question: Tenho uma tabela no banco chamada Cota, essa cota tem duas colunas uma para data_inicio e data_fim, até aqui tudo bem, agora eu tenho outra tabela chamada Ordem que tambem tem data_inicio e data_fim, essas tabelas são relacionadas 1 para N, uma cota pode ter N Ordens, criei uma validação para não deixar o usuario criar uma ordem que não seja maior ou menor que a data da cota cadastrada, toda ordem precisa estar dentro do intervalo cadastrado na Cota, meu problema é que também não posso deixar o usuario cadastrar uma ordem que entre dentro do intervalo de otra ordem, exemplo:
Data da Cota: data_inicio 10/08/2017 e data_fim: 20/08/2017
1: Data da Ordem: data_inicio 11/08/2017 e data_fim: 15/08/2017
Aqui esta o problema:
2: Data da Ordem: data_inicio 13/08/2017 e data_fim: 17/08/2017
A data_inicio 13/08/2017 dessa ultima ordem entrou no intervalo da 1 Ordem: data_inicio 11/08/2017 e data_fim: 15/08/2017 isso não pode ocorrer.
Existe algum método ou alguma solução para isso, sugesão de melhoria ?
Aqui está o metodo com algumas validações que fiz.
 public void ValidarDataDaOrdem(decimal idCota, DateTime dataInicio, DateTime dataFim)
    {
        var cota = Context.Cota.Include("Ordem").Where(e => e.IdCota == idCota).FirstOrDefault();
        var ordens = cota.Ordem.ToList();

        if (dataInicio < cota.dataInicioCota)
        {
            throw new InfoException("Data Inico tem que ser maior que a data inicio da cota");
        }
        if (dataFim > cota.DataFimCota)
        {
            throw new InfoException("Data Final tem que ser menor que a data final da cota");
        }

        foreach (var item in ordens)
        {
            if (item.DataInicioOrdem == dataInicio && item.DataInicioOrdem == DataFim)
            {
                throw new InfoException("Ja existe solicitação cadastrada para esse periodo");
            }
            if (item.DataInicioOrdem == dataInicio || item.DataInicioOrdem == DataFim)
            {
                throw new InfoException("Ja existe solicitação cadastrada para essa data");
            }
        }
    }

Answer: Imagino que você esteja validando as datas de entrada no client, ainda assim, sendo uma informação condicional da funcionalidade, deveria validar novamente no server.
Não testei efetivamente, mas creio que algo assim pode ajudá-lo:
public void ValidarDataDaOrdem(decimal idCota, DateTime dataInicio, DateTime dataFim)
{
    var cota = Context.Cota.Include("Ordem").Where(e => e.IdCota == idCota).FirstOrDefault();

    if(dataInicio > dataFim || dataInicio < cota.DataInicio  || dataInicio > cota.DataFim || dataFinal > cota.DataFinal || dataFinal < cota.DataInicio)
        throw new InfoException($"Datas informadas fora do intervalo permitido [De: {cota.DataInicio} à {cota.DataFim}");

    if(cota.Ordem.Where(item=> dataInicio >= item.dataInicioOrdem && dataInicio <= item.dataFimOrdem).count() > 0)
        throw new InfoException("Já existe uma solicitação cadastrada para este período.");
}

Você poderia pesquisar por linq e lambda pra utilizar melhor as questões de filtros e etc. Melhorar as queries de uma maneira geral. É muito simples e produtivo. (=
Answer: Eu recomendo substituir esse trecho:
foreach (var item in ordens)
{
    if (item.DataInicioOrdem == dataInicio && item.DataInicioOrdem == DataFim)
    {
        throw new InfoException("Ja existe solicitação cadastrada para esse periodo");
    }
    if (item.DataInicioOrdem == dataInicio || item.DataInicioOrdem == DataFim)
    {
        throw new InfoException("Ja existe solicitação cadastrada para essa data");
    }
}

Por:
var ordemEmChoque = ordens.FirstOrDefault(o =>
    (o.DataInicioOrdem <= dataInicio && o.DataFimOrdem >= dataInicio) ||
    (o.DataInicioOrdem <= dataFim && o.DataFimOrdem >= dataInicio)
);
if (ordemEmChoque != null) {
    throw new InfoException("Já existe uma solicitação cadastrada com choques " +
        "de data para a nova solicitação. A solicitação já existente é a de número" + foo);
}

Onde foo é uma identidade ou código que identifique uma ordem já existente.

Intervalo de datas C#


Are there reasons to choose between a round-section or an octogonal-section bow?

Question: The initial part of a violin, viola, or cello bow in modern models is always octogonal, but
the rest of the stick can be either of round section or octogonal-faceted.
Is it simply a different external design, a different school of bow-making, or something more?
Are there reasons to select one or the other in term of sound production or control?
Answer: A few years ago I asked this exact question to the archetier who made my bow.
According to him, bow weight and flexibility are the things to have in mind when having a bow built. These are the things that make a difference in a bow.
Now about it being round or octagonal, it was a purely aesthetic decision. The bow can be heavier or lighter, jumpy or stiff, and still be either round or octagonal. This question is in the same league as "should my bow have silver ornaments or some cheaper metal?" and "how detailed should the mother-of-pearl engraving be?". Purely aesthetic.
ADDENDUM:
Sure enough, I called my archetier and he confirmed that it's an aesthetic question. There are factors to have in mind that differ when building the bow, but the way it works is all the same. Mind you this answer comes from a guy who makes bows for a living, whose father made bows for a living before him and etc. Plus half the orchestra I work at uses his bows, so I guess it's a pretty reliable source.
Comment: I hear you but I doubt that the choice between round and octagonal is purely esthetic, and in any case it cannot be put on the same level than decorative elements. It may not affect the sound (I want to know more and I have not seen hard evidence in one way or the other) but it certainly affects the build process and the tools used and, as it affects the shape of the stick, it cannot be easily dismissed as aesthetic without more references. Do you now a bowmake that would be willing to answer us here ?
Comment: It was my bowmaker the one who told me what I said. Here's to settle it: I'll call him on Monday and ask again. It won't be _the_ definitive answer but atleast it'll be the answer of someone who makes bows for a living.
Comment: I'm a bowmaker and I can confirm that while there is theoretically a difference in stiffness between an octagonal and a round bow, the difference is so slight that it is not perceptible or measurable.  And the construction techniques are basically the same, since the normal procedure is to make a stick octagonal first even if it's going to be round when finished.


Does there exist polynomials $P$ s.t. $P(k)\mid k!$ holds for only finitely many $k\in\Bbb N$?

Question:
Question: Does there exist polynomials $P$ with integer coefficients such that  $$P(k)\mid k!\tag{*}$$ holds for only finitely many $k\in\Bbb N$?

I think such polynomial doesn't exist (don't know how to prove it). For some specific polynomials, we can prove there exists infinitely many $k\in\Bbb N$ satisfying $(*)$ by constructing $k=\text{a polynomial}$:

Example: $P(k)=k^n-1$, $n\in \Bbb N$

Choose distinct primes $p_1,p_2,\dots,p_j$ coprime to $n$ such that
$$\ell=\prod_{i =1}^j \frac{p_i-1}{p_i}<\frac 1n.$$
Let $m=p_1p_2\cdots p_j$ and $k=r^{m}$, $r\in\Bbb N$, then
$$P(k)=P(r^m)=r^ {mn}-1=\prod_{d\mid mn
}\Phi_d(r),$$
where $\Phi_d(r)$ are cyclotomic polynomials. Note that
$$\deg \Phi_d=\phi(d)\le \phi(mn)\le m\phi(n)\le mn \ell<m,$$
Therefore for integer $r>N$, we have $r^m>\Phi_d(r)$ and thus
$$\left(\prod \Phi_d(r)\right)\mid\left(r^m\right)!\quad \iff\quad k^n-1\mid k!.$$

With the aid of Mathematica, "surprisingly" I found that the growth rate of the number of integers smaller than $n$ satisfying $(*)$ approximately equals $C\cdot n$ for some constants $C$:
\begin{align*}
P(k)&=k^2-1,\quad \#(k\le n \text{ satisfying } (*))\sim 0.85 n,\\
P(k)&=k^2+1,\quad \#(k\le n \text{ satisfying }(*))\sim 0.23 n.
\end{align*}
Here are some graphs for different $P$:
$x$-axis: $n$
$y$-axis: $\#(k\le n\text{ satisfying }(*))$

Graph 1: $P(k)=k^2-1$

Graph 2: $P(k)=k^6-6k^4+9k^2-1$

Conjecture: For any polynomial $P$ with integer coefficients, there are infinitely many $k\in \Bbb N$ satisfying $(*)$, and the growth rate
  $$\#(k\le n\text{ satisfying }(*))\sim C\cdot n$$
  for large $n$ and a constant $C$.
Comment: Good question. I think, however, it is open for general polynomials of degree bigger than $2$. The key phrase one is looking for is "smooth values of polynomials". If $P(x)$ has degree $d$, then one (at least) wants all the prime factors of $N = P(n)$ to be at most $N^{1/d}$ for infinitely many values of $n$. This is certainly conjectured to be true, but is an open problem. It is known for quadratic polynomials, however. Here's at least one reference: https://arxiv.org/pdf/1710.01970.pdf
Comment: My code for producing the plots and calculating the gradient (Mathematica):$$
ClearAll[a];  \\
a[1] = 0;  \\
a[n_] := a[n] = a[n - 1] + If[Divisible[n!, n^2 - 1], 1, 0]  \\
ListLinePlot[Table[a[n], {n, 10000}]]\\
a[10000]/10000.\\$$
Comment: Do you have the code for producing these plots/calculating the gradient?
Answer: We will be looking at different values of $\mathrm{deg}(P)$ where $P \in \mathbb{Z}(x)$. For $\mathrm{deg}(P)=0$, the question is trivial as $\forall$ $x \geqslant c$ where $P(x)=c$ , we will have $P(x) \mid x!$

Claim: There are infinitely many $x$ such that $P(x) \mid x!$ where $P \in \mathbb{Z}[x]$ and $\deg(P)=1$.
Let $P(x)=ax+b$ for $a,b \in \mathbb{Z}$. We have:
$$P(bx)=a(bx)+b = b(ax+1)$$
It suffices to show that $P(bx) \mid (bx)!$ infinitely often.
$$P(bx) \mid (bx)! \iff b(ax+1) \mid (bx)! \iff (ax+1) \mid (bx-1)!$$
since $b \mid bx$ and $\gcd(ax+1,x)=1$. Now, since $a$ is finite in magnitude, we choose a prime $p$ such that $p \nmid a$. Next, we set:
$$x=\frac{p^{k\phi(a)}-1}{a}$$
Clearly, $x$ is integral $\forall$ $k \in \mathbb{N}$ since $a \mid p^{\phi(a)}-1 \mid p^{k\phi(a)}-1$. Now, we have:
$$ax+1=p^{k\phi(a)} \implies \nu_p(ax+1)=k\phi(a)$$
$$\nu_p((bx-1)!)=\sum_{i=1}^\infty \bigg\lfloor\frac{bx-1}{p^i} \bigg\rfloor>\frac{bx-1}{p}-1=\frac{b(p^{k\phi(a)}-1)}{a}-\frac{p+1}{p}$$
We see that the power of $p$ that divides $ax+1$ is a polynomial in $k$ while the power dividing $(bx-1)!$ is an exponential. Thus, $\exists$ sufficiently large $M$ s.t. $\forall$ $k \geqslant M$, we have $(ax+1) \mid (bx-1)!$.
QED

Now, we call a polynomial smooth if there are infinitely many $x$ s.t. all the primes dividing $P(x)$ are less than $x^\epsilon$ $\forall$ $\epsilon>0$. We can see:
$(i)$ If $P(x) \mid x!$ for infinitely many $x \in \mathbb{N}$, then $P$ is specifically smooth for $\epsilon = 1$
Proof : For prime $p$, we have $p \nmid x! \iff p>x$. Thus, we will have $p \nmid P(x)$ infinitely often for any $p>x$ which shows specific smoothness at $\epsilon=1$.
$(ii)$ If $P$ is smooth, then $P(x) \mid x!$ for infinitely many $x \in \mathbb{N}$.
Proof : We can find sufficiently large $M$ s.t. $x^M > P(x)$ $\forall$ $x>1$ where $x$ is a positive integer. Since $P$ is smooth, we can have $\epsilon = \frac{1}{k}$ for sufficiently small $k$. This means that any prime $p$ dividing $P(x)$ satisfies $p<x^\frac{1}{k}$ for infinitely many $x$ which will be the values we will consider. Thus:
$$\log_p(x)<\log_p(x^M)=M\log_p(x) \tag{1}$$
$$\nu_p(x!)=\sum_{i=1}^\infty \big\lfloor\frac{x}{p^i} \big\rfloor > \frac{x}{p} \tag{2}$$
We can see that $\frac{x}{p}>M\log_p(x) \iff \frac{x}{M\log_p(x)}>p$. However, we know that $x^\frac{1}{k}>p$ and $\frac{x}{M\log_p(x)}>x^\frac{1}{k}$ will hold infinitely often by comparison of power of $x$ on both sides. Thus, we are done.

Our problem has been solved for $\mathrm{deg}(P)<2$ above. For $\mathrm{deg}(P)=2$, one can refer the paper which is attached below (also present in first comment of OP's question).
Proof for $\mathrm{deg}(P)=2$ : Smoothness of Quadratic Polynomials
For $\mathrm{deg}(P)>2$, we are to first try to prove the weaker condition of specific smoothness of higher degree polynomials for $\epsilon=1$. However, this seems to be an open problem, only solvable for specific polynomials (such as the example provided by OP) based on the looks of the above paper and personal search and browsing by myself and @TheSimpliFire. Thus, we finally conclude:

The problem has an affirmative answer for $\mathrm{deg}(P) \leqslant
 2$ and is open for $\mathrm{deg}(P) > 2$ due to no answer for specific
   smoothness of integer-coefficient polynomials for $\epsilon=1$.


How to get div to render on top of an image?

Question: How can I make a horizontal bar of image links to render over an image? Like this:

Each icon should redirect to its corresponding page, and the header image itself is a .svg so whitespace doesn't render => I don't think z-index will be necessary
Comment: just post the code whatever you have tried
Comment: Questions seeking code help must include the shortest code necessary to reproduce it **in the question itself** preferably in a [**Stack Snippet**](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/).  See [**How to create a Minimal, Complete, and Verifiable example**](http://stackoverflow.com/help/mcve)
Answer: What i think you intended to do is to position the links on top of the background image.
So i prepared this small example.
Also, it's a good idea to add some kind of visual feedback when the user hovers the icons that he will understand that they are clickable :)

.background {
  position: relative;
}
.links {
  position: absolute;
  list-style-type: none;
  bottom: 30px;
  left: 50px;
}
.links li {
  display: inline;
}
a {
  text-decoration: none;
}
a img {
  padding: 0 15px;
}
a:hover img {
  transform: scale(1.2);
  -ms-transform: scale(1.2);
  -webkit-transform: scale(1.2);
}


Is the ratio of two positive (non zero functions) quasiconvex or convex?

Question: I am trying to minimize the below function, can it be considered quasiconvex and/or convex?
$$F(\mathbf{x})= \frac{|\mathbf{a}^T\mathbf{\Sigma}\mathbf{x}|}{\mathbf{x}^T\mathbf{\Sigma}\mathbf{x}}$$
where $\mathbf{a},\, \mathbf{x}$ are real-valued vectors and $\mathbf{\Sigma}$ is a positive-definite matrix.
I know that the numerator is convex (absolute value of affine) and the denominator is convex and positive.
Comment: Please don't delete questions and re-post them. This question is better formatted, but you could have edited the previous post.
Answer: This ratio is in general not (quasi)convex. Consider dimension $n = 1$ and $\Sigma = a = 1$. You end up with
$$
F(x) = \frac{|x|}{x^2} = \frac{1}{|x|}.
$$
This cannot be (quasi)convex, since its sublevel sets are not convex. For example:
$$
F_{1} := \left\{x \mid F(x) \leq 1 \right\} =
\{x \mid |x| \geq 1 \} = (-\infty, -1] \cup [1, \infty),
$$
which is a disjoint union of intervals and as such nonconvex.
Answer: No, this function is not quasiconvex; as I pointed out last time you asked the question, the domain is not convex. This prevents sublevel sets being convex, and so the function cannot be quasiconvex.
As you are trying to minimise the function, the unfortunate issue is that the function has no minimum. Consider the sequence of vectors:
$$\mathbf{x}_n = -\frac{1}{n}\mathbf{a}.$$
Then
$$F(\mathbf{x}_n) = \frac{-\frac{1}{n}\mathbf{a}^\top \mathbf{\Sigma}\mathbf{a}}{\frac{1}{n^2}\mathbf{a}^\top \mathbf{\Sigma}\mathbf{a}} = -n \to -\infty.$$
Thus, the function is unbounded below, and no minimum, or even finite infimum, exists.


Correct place to store key pairs for SSH authentication with VPS (Cygwin and Linux)

Question: I am using Cygwin on windows 10 to try and ssh into my Linux server for the first time. I have a public and private key pair called whm_rsa and whm_rsa.pub in user/user/.ssh on my local computer.
Using WHM I have imported the key pair with 'manage roots SSH keys' and authorized the public_key.
The user@..  I am trying to log into is a sub-account of root.
I have also logged into the CPanel for the sub-account and added the key pair and authorized the public key.
Below is the log could someone show me where I have gone wrong?
$ ssh name@*** -v -v -v
    OpenSSH_7.5p1, OpenSSL 1.0.2k  26 Jan 2017
    debug2: resolving "***.**.*" port 22
    debug2: ssh_connect_direct: needpriv 0
    debug1: Connecting to ***.**.* [***.**.*] port 22.
    debug1: Connection established.
    debug1: identity file /home/user/.ssh/id_rsa type 1
    debug1: key_load_public: No such file or directory
    debug1: identity file /home/user/.ssh/id_rsa-cert type -1
    debug1: key_load_public: No such file or directory
    debug1: identity file /home/user/.ssh/id_dsa type -1
    debug1: key_load_public: No such file or directory
    debug1: identity file /home/user/.ssh/id_dsa-cert type -1
    debug1: key_load_public: No such file or directory
    debug1: identity file /home/user/.ssh/id_ecdsa type -1
    debug1: key_load_public: No such file or directory
    debug1: identity file /home/user/.ssh/id_ecdsa-cert type -1
    debug1: key_load_public: No such file or directory
    debug1: identity file /home/user/.ssh/id_ed25519 type -1
    debug1: key_load_public: No such file or directory
    debug1: identity file /home/user/.ssh/id_ed25519-cert type -1
    debug1: Enabling compatibility mode for protocol 2.0
    debug1: Local version string SSH-2.0-OpenSSH_7.5
    debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1
    debug1: match: OpenSSH_6.6.1 pat OpenSSH_6.6.1* compat 0x04000000
    debug2: fd 3 setting O_NONBLOCK
    debug1: Authenticating to ***.**.*:22 as 'name'
    debug3: hostkeys_foreach: reading file "/home/user/.ssh/known_hosts"
    debug3: record_hostkey: found key type ECDSA in file /home/user/.ssh/known_hosts:2
    debug3: load_hostkeys: loaded 1 keys from ***.**.*
    debug3: order_hostkeyalgs: prefer hostkeyalgs: email@example.com,ecdsa-sha2-nistp384-cert-v01@opensshdsa-sha2-nistp384,ecdsa-sha2-nistp521
    debug3: send packet: type 20
    debug1: SSH2_MSG_KEXINIT sent
    debug3: receive packet: type 20
    debug1: SSH2_MSG_KEXINIT received
    debug2: local client KEXINIT proposal
    debug2: KEX algorithms: curve25519-sha256,firstname.lastname@example.com,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp12,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha
    debug2: host key algorithms: email@example.com,firstname.lastname@example.com,ecdsa-sha2-niecdsa-sha2-nistp521,email@example.com,email@example.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-
    debug2: ciphers ctos: firstname.lastname@example.com,aes128-ctr,aes192-ctr,aes256-ctr,email@example.com,aes256-gcm@opens
    debug2: ciphers stoc: firstname.lastname@example.com,aes128-ctr,aes192-ctr,aes256-ctr,email@example.com,aes256-gcm@opens
    debug2: MACs ctos: firstname.lastname@example.com,email@example.com,email@example.com,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
    debug2: MACs stoc: firstname.lastname@example.com,firstname.lastname@example.com,firstname.lastname@example.com,email@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
    debug2: compression ctos: none,firstname.lastname@example.com,zlib
    debug2: compression stoc: none,email@example.com,zlib
    debug2: languages ctos:
    debug2: languages stoc:
    debug2: first_kex_follows 0
    debug2: reserved 0
    debug2: peer server KEXINIT proposal
    debug2: KEX algorithms: firstname.lastname@example.com,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellmanlman-group14-sha1,diffie-hellman-group1-sha1
    debug2: host key algorithms: ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519
    debug2: ciphers ctos: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,firstname.lastname@example.com,firstname.lastname@example.com,c8-cbc,aes192-cbc,aes256-cbc,arcfour,firstname.lastname@example.com
    debug2: ciphers stoc: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,firstname.lastname@example.com,firstname.lastname@example.com,c8-cbc,aes192-cbc,aes256-cbc,arcfour,email@example.com
    debug2: MACs ctos: email@example.com,email@example.com,email@example.com,email@example.com,firstname.lastname@example.com,email@example.com,email@example.com,hmac-md5,hmac-sha1,firstname.lastname@example.com,umac-128@firstname.lastname@example.com,hmac-sha1-96,hmac-md5-96
    debug2: MACs stoc: email@example.com,email@example.com,email@example.com,email@example.com,email@example.com,firstname.lastname@example.com,email@example.com,hmac-md5,hmac-sha1,firstname.lastname@example.com,umac-128@email@example.com,hmac-sha1-96,hmac-md5-96
    debug2: compression ctos: none,email@example.com
    debug2: compression stoc: none,firstname.lastname@example.com
    debug2: languages ctos:
    debug2: languages stoc:
    debug2: first_kex_follows 0
    debug2: reserved 0
    debug1: kex: algorithm: firstname.lastname@example.com
    debug1: kex: host key algorithm: ecdsa-sha2-nistp256
    debug1: kex: server->client cipher: firstname.lastname@example.com MAC: <implicit> compression: none
    debug1: kex: client->server cipher: firstname.lastname@example.com MAC: <implicit> compression: none
    debug3: send packet: type 30
    debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
    debug3: receive packet: type 31
    debug1: Server host key: ecdsa-sha2-nistp256 SHA256:tUFGb9yC/wlQC5JMGedvPz5GxjMb+6bKgY05b1qkWMc
    debug3: hostkeys_foreach: reading file "/home/user/.ssh/known_hosts"
    debug3: record_hostkey: found key type ECDSA in file /home/user/.ssh/known_hosts:2
    debug3: load_hostkeys: loaded 1 keys from ***.**.*
    debug1: Host '***.**.*' is known and matches the ECDSA host key.
    debug1: Found key in /home/user/.ssh/known_hosts:2
    debug3: send packet: type 21
    debug2: set_newkeys: mode 1
    debug1: rekey after 134217728 blocks
    debug1: SSH2_MSG_NEWKEYS sent
    debug1: expecting SSH2_MSG_NEWKEYS
    debug3: receive packet: type 21
    debug1: SSH2_MSG_NEWKEYS received
    debug2: set_newkeys: mode 0
    debug1: rekey after 134217728 blocks
    debug2: key: /home/user/.ssh/id_rsa (0x2005f510)
    debug2: key: /home/user/.ssh/id_dsa (0x0)
    debug2: key: /home/user/.ssh/id_ecdsa (0x0)
    debug2: key: /home/user/.ssh/id_ed25519 (0x0)
    debug3: send packet: type 5
    debug3: receive packet: type 6
    debug2: service_accept: ssh-userauth
    debug1: SSH2_MSG_SERVICE_ACCEPT received
    debug3: send packet: type 50
    debug3: receive packet: type 51
    debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic
    debug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-mic
    debug3: preferred publickey,keyboard-interactive,password
    debug3: authmethod_lookup publickey
    debug3: remaining preferred: keyboard-interactive,password
    debug3: authmethod_is_enabled publickey
    debug1: Next authentication method: publickey
    debug1: Offering RSA public key: /home/user/.ssh/id_rsa
    debug3: send_pubkey_test
    debug3: send packet: type 50
    debug2: we sent a publickey packet, wait for reply
    debug3: receive packet: type 51
    debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic
    debug1: Trying private key: /home/user/.ssh/id_dsa
    debug3: no such identity: /home/user/.ssh/id_dsa: No such file or directory
    debug1: Trying private key: /home/user/.ssh/id_ecdsa
    debug3: no such identity: /home/user/.ssh/id_ecdsa: No such file or directory
    debug1: Trying private key: /home/user/.ssh/id_ed25519
    debug3: no such identity: /home/user/.ssh/id_ed25519: No such file or directory
    debug2: we did not send a packet, disable method
    debug1: No more authentication methods to try.
    Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

Comment: "Sub-account of root"? Things that would be useful (Assuming server is running OpenSSH) (All from the server): /etc/ssh/sshd_config, the SSH logs (possibly with debugging), checks that ~/.ssh/authorized_keys contains the correct public keys, permissions for the home directory, ~/.ssh and ~/.ssh/authorized_keys... (SSH is using the key from /home/user/.ssh/id_rsa in this case)
Answer: If you want to use a private key called whm_rsa in the .ssh directory, you need to pass -i ~/.ssh/whm_rsa to your SSH client. (The keys it will try by default all start with id_)
(On Windows, PuTTY might be easier to deal with than OpenSSH under Cygwin...)
Comment: Thanks this might have been my problem, will check it out asap.
Comment: I'm assuming `bash`, which will expand `~` to your home directory. Also, if you decide on PuTTY instead, keys needs to be converted... (This can be done in PuTTYgen)


Set the default value for a password field on a custom form

Question: I have created a custom user register form. I want to set the default value for the password, and confirm the password fields.
My point is that, whenever form error occurs, the password fields get cleared. Users don't need to type the password again and again.
Answer: If you are using password as form element type for the password, it does not support the #default_value property. The password field  is cleared when there is a validation error.