c++ object instantiation using sizeof, malloc and cast

Question: In Java I can instantiate an object using the 'Class' method 'newInstance' which for my particular system I find very helpful indeed. I am now trying to achieve something similar in C++.
It has not been obvious to me how this might be achieved but after some reflection .... (do you get it ... huh?) I think that it might be possible by creating a ClassDescription class which has an attribute holding the 'sizeof' the class instance and a method newInstance which mallocs this amount of memory and returns it as a void *. The calling code will then need to cast this appropriately.
Does the C++ language suitably define whether this is valid?
By the way .. I recognise that I could create a registry holding Factories for the classes which is a backup plan. For answers to this question I would value focusing on the specific question of whether what I have discussed will work.
Best Regards
* Additional Context *
The reason for this requirement is to allow a generic library to instantiate classes which the library user is aware of but not the library itself. The library will have some meta data to use to achieve this and so could be told the sizeof the class. It is 'neater' from the user perspective not to have to add a factory object to the the meta data.
Comment: Why don't you just give your class a private constructor and call `new Class` from a static method?  Don't use malloc, it won't call the classes constructor for you.
Comment: Are you asking why `malloc` is not used to allocate object instances in C++?
Comment: If you want to go down this route then you should look into [placement new](http://stackoverflow.com/questions/222557/cs-placement-new)
Comment: @Benj Unfortunately the calling library does not know the classes it needs to instantiate.
Comment: @Cody No, rather I am asking whether it is possible to do this.
Comment: To expand Benj's answer, instead of passing the sizeof of a class to the library, pass function pointers to static members of the class that use `new`.
Comment: You're going to have to add an object of some sort to store the size information etc., instead of storing the size in that object why not just store a `std::function` that handles the creation.
Answer: This would be valid in some instances. The requirement is that the type must be a "plain old data type" (POD) (see also this answer). If it has anything more complicated (e.g. virtual member functions, members which have virtual member functions, base classes must also be POD etc.) then it will not work and is undefined behaviour.
You can check if a type meets these requirements by doing:
#include <type_traits>

static_assert(std::is_pod::value, "A must be a POD type.");

In general though it probably indicates that you're doing it wrong. C++ isn't Java and there's probably a much better way to solve the underlying real problem.
Comment: your link says that `type_traits` is c++11 ... in that case, it will limit the usefulness of this approach...
Comment: @user1055604 - boost has a `is_pod`, but its usefulness is somewhat limited pre-C++11 IIRC. You can always do it without the assert if you're willing to make that bet on your own. And MSVC and recent GCC as well as clang all support this. It's also in TR1 I believe, which pre-dates C++11 somewhat. This answer lists the requirements for this type of behaviour to be legal and shows how you can verify they've been met in code.
Answer: What you're missing in the malloc and cast method is the construction of the object. Using new both allocates memory and constructs it. This includes building v-tables, calling the constructor and so on. Type casting malloc allocated memory is not valid.
Answer: Note that mallocing a memory block of the right size gives you just raw memory. You need to construct an object of the desired class in this memory block. This can be achieved using placement new.


How to change the local code Link?

Question: I am using the Aqcuia Dev Desktop where near to the local code label is written the following link: ( C:\Users\Wessam\DrupalSites\devdesktop\drupal-7.34 )
lets say that i want to move my drupal localhost site files & folders to another folder so it will be under the following link: ( C:\Users\Wessam\AllSites\CompanyName ) so the link near to the local code label should be changed also...
How to do the mentioned above?
Answer: 1)
Follow the Path below:
C:\Program Files (x86)\DevDesktop\AcquiaDevDesktop\datamodel.xml
2)
Open the " datamodel.xml " using the Notepad++ or any other similar programming language editor program
3)
Edit the Link written within:
 HERE HERE HERE
 HERE HERE HERE
to any link required by you .
Answer: Generally there is no problem if you have a good programming! Clearly the url of your local site will be changed but the question is, how did you refer to your site?
I mean if the old url is localhost/old-version, Have you ever used this url in your template files or js files? if yes then you should replace  them by new url. I recommend you to use
<?php
      global $base_url;
?>

I have moved my website from a server to another server with new domain and no problem happened (only some trivial changes were needed) because I always use relative paths.

How to change the local code Link?


How can I find out whether a number is a quadratic residue in a large modulo?

Question: Without strenuous arithmetic.
Is there a program I can download to do so?
What are the quadratic residues modulo $5^4$ or $5^5$?
Thanks!
Comment: http://www.wolframalpha.com/input/?i=what+are+the+quadratic+residue+modulo+3125 for example.
Answer: The Euler criterion is easily generalized to yield the following test for squareness $\!\rm\bmod n$.
Theorem $\ $ Let $\rm\ a,\:n\:$ be integers, with $\rm\:a\:$ coprime to $\rm\:n\ =\ 2^e p_1^{e_1}\cdots p_k^{e_k},\, \ p_i\,$ primes.
$\rm\quad\quad \ x^2\ =\ a\pmod{n}\, $ is solvable for $\rm\:x\:$
$\rm\quad\quad \: \iff\ \ \: a^{(p_i\ -\ 1)/2} \ \ \equiv\ \ 1\ \ (mod\ p_i)\quad\quad\ \ $  for all $\rm\ i\le k$
$\quad\quad\ $ and $\rm\quad\ \ e>1 \:\Rightarrow\: a\equiv 1\ \ (mod\ 2^{2+\delta}\:),\ \ \ \delta = 1\ \ if\ \ e\ge 3\ \ else\ \ \delta = 0$
Proof: See Ireland and Rosen,  A Classical Introduction to Modern Number Theory, Proposition 5.1.1 p. 50.
The above criterion is practical if one knows a full factorization of $\rm\:n\:$, since the exponentiations may be quickly computed by repeated squaring.
Beware $\ $ The criterion cannot be expressed equivalently as a simple Jacobi symbol calculation. For example we have $\rm(8|15) = 1\ $ but $8$ is not a square (mod $15$).
Comment: Just in case anyone got confused like me, to be clear, if `n = 2^1 * 3^1 * 5^0 * 7^1`, then `p_i = {3, 7}`, NOT `{3, 5, 7}`
Answer: If you want to know the squares modulo $p^m$ where $p$ is an odd prime,
they are congruent to $0$ or to numbers $a p^{2k}$ where $0\le k < m/2$
and the Legendre symbol $\left(\frac ap\right)=1$. For large primes $p$,
Legendre symbols can be calculated by regarding them as
Jacobi symbols and using the law of quadratic reciprocity
for Jacobi symbols.
I don't regard $5$ as a large prime. :-)
Comment: And there are many freely available software packages that use arbitrary-precision integers and can efficiently compute Legendre symbols.  In linux, Pari would be one.  The underlying code is called the GNU Multi-Precision library.  As Asaf Karagila points out, there are on-line applications as well.
Comment: Pari is also available for Windows and Mac OS X.
Answer: Here is some code for answering whether $a$ is a quadratic residue modulo $n$, that correctly handles the case when $\gcd(a, n) > 1$, and also when $a$ or $n$ may be negative (except of course $n$ can't be zero).
def peel(a, p):
    # Returns (k, b) such that a = p^k * b and b is minimal.
    if a == 0: return (1, 0)
    k = 0
    while a % p == 0:
        k += 1
        a = a // p
    return (k, a)

def is_quadratic_residue(a, n):
    for (p, e) in factor(n):
        (k, b) = peel(a % p**e, p)
        if b == 0: continue
        if k % 2: return False
        if p == 2:
            if e == 1: continue
            if b % 4 != 1: return False
            if e >= 3 and b % 8 != 1: return False
        else:  # Euler's criterion
            if power_mod(b, (p - 1)//2, p) != 1:
                return False
    return True

As you can see above, it is written in Python, and further relies on two functions (which are available in Sage, but if you're using this elsewhere you'd have to implement yourself):

a factor(n) which returns a list of pairs (p, e) such that the product of these $p_i^{e_i}$ is $n$ — for example, factor(126) returns [(2,1), (3,2), (7,1)] because $126 = 2^1 3^2 7^1$.
a power_mod(x, n, p) that returns $x^n \bmod p$. This is easy to implement yourself using repeated squaring.
it relies on the fact that a % m always returns a positive result when m is positive, even if a is negative. This is how Python does it, but if you're using one of the languages that do it differently, you may have to change some of the definitions (not a big deal; instead of x % p != 1 you can check (x - 1) % p != 0).

A sidenote: you may wonder whether it's possible to answer whether $a$ is a quadratic residue mod $n$, without factoring $n$. If it were possible to do so and also find a square root when $a$ is a quadratic residue, then this would give an algorithm for factoring: pick random $x$ and ask whether $x^2 \bmod n$ is a quadratic residue; if you get a square root $y$ then with probability $1/2$ the fact that $x^2 \equiv y^2 \pmod n$ gives a nontrivial factorization of $n$ by taking $\gcd(n, x-y)$. For only answering yes or no (the quadratic residuosity problem), it is believed to be hard as well (not known whether it is equivalent to factoring, and not known to be easier than factoring).
Comment: **Note** the code is simply a Python implementation of the Theorem in my answer (posted $9$ years prior).
Comment: The remark about factoring $n$ given a nontrivial square root is also $9$ years old, e.g. see [here](https://math.stackexchange.com/a/4604/242) where more general results are proved.
Comment: @BillDubuque Yes indeed, my main reason for posting an answer with the Python code is that I kept needing it, but every time I looked it up from scratch I'd keep finding answers assuming $\gcd(a, n) = 1$ or that $a, n > 0$ (and not being clear about whether these assumptions mattered). So (for reasons of practical usability) I wanted to do the grunt work carefully and write it down for the general case once, as future reference.
Comment: @BillDubuque (Also the question asked "Is there a program I can download to do so?" which is probably why I posted it here rather than on some other question.)


Moving a div/button with jquery

Question: I have made  a slide out sidebar that comes out when you press a button/div but I want the button / div to slide out with it too here is what I have tried

<meta name="viewport" content="width=device-width"/>

BillIsChill

<?php include('sidebar.html');?>

<link type="text/css" rel="stylesheet" href="desktopstyle.css" />
<link type="text/css" rel="stylesheet" href="style_darkcyan.css" />
<link type="text/css" rel="stylesheet" href="sidebarBETA.css" />

and here is my relevant style that i am using
#menubutton.open{
right: 205;
}
#menubutton{
display-inline;
width:50px;
height:50px;
background:#006666;
float:right;
border-radius:10px;
margin-top: 5px;
margin-bottom: 5px;
margin-right:5px;
right: 5px;

}
#menubutton:hover{
background:cadetblue;
}
#sidebarright.open{
right: 1;
}
#sidebarright{
 background: darkcyan;
 text-align: center;
 z-index: 2;
 position: fixed;
 height: 100%;
 width: 200px;
 float: right;
 top: 0;
 overflow-y: scroll;
 overflow-x: hidden;
 transition: right 0.5s;
 right:-200;
 }

Can someone please help me
Comment: Can you please add the HTML?
Comment: Although you could join the two event handlers together, there's nothing immediately wrong with the code you've shown. The issue must lay elsewhere in your CSS or JS code. Unfortunately no one can help you unless you edit your question to show that code.
Comment: It's just a div styled to look like a menu button and stuff for the header and linking style and php
Answer: This works

One

Two

Three

  <button id="button">Click</button>

Comment: i cant seem to get a smooth transition to work in css
Comment: it does the same thing im not shure what to do sir
Comment: Not sure why, but it doesn't want to save my changes. Therefore I created a new one: https://jsfiddle.net/beekvang/3xy28adn/
Comment: Ok i am very sorry but the button is still not sliding out with the sidebar, the sidebar slides out (wich is very nice by the way) but the button sort of fades off to the right here is my site [link](http://billischill.ddns.net) and the code has been updated above
Answer: I think code blocks are not properly formatted. But below css should fix your issue.
#menubutton.open{
   right: 205;
}
#menubutton{
   display-inline;
   width:50px;
   height:50px;
   background:#006666;
   float:right;
   border-radius:10px;
   margin-top: 5px;
   margin-bottom: 5px;
   margin-right:5px;
   right: 5px;
}
#menubutton:hover{
   background:cadetblue;
}
#sidebarright.open{
   right: 1;
}
#sidebarright{
   background: darkcyan;
   text-align: center;
   z-index: 2;
   position: fixed;
   height: 100%;
   width: 200px;
   float: right;
   top: 60px;
   overflow-y: scroll;
   overflow-x: hidden;
   transition: right 0.5s;
   right:-200;
   overflow: auto;
 }
 #header1 {
  z-index: 3;
 }

Moving a div/button with jquery


Choose a digital piano

Question: I am playing piano for 5 years now and I am moving away from my parents' place and the upright piano they have. Help me to choose a Roland digital keyboard. No more than 1500 €.
Is there a big difference between the F130r and the F140r? I think it is a pretty good one and not so expensive. And is the RP401r better? (found one just a hundred euro more expensive)
Then I found a second hand HP506 from 2013. A bit more expensive. Does it have more functions? Does it sounds better? Or feels like a real piano? I also found a new HP504 for the same price.
I am quite lost in the bunch of characteristic for me they all have the same functions. Any advice on these piano.
Answer: As I understand, advice on specific equipment is outside the scope of this forum. However I can perhaps give some general advice on the concerns you may need to have when making your choice, assuming your main purpose is to use the instrument to practice piano technique.
First of all,  DON'T make your decision without trying the actual instrument you may be buying. Much like an acoustic piano (or perhaps more), the feel of the keyboard varies considerably by manufacturer and model.
The sound also varies a lot, but it's perhaps less important for practice. It will be extremely difficult, not to say impossible, to further your studies beyond a certain point with a digital piano only anyway. So if the keyboard is suitably responsive, for general technical practising such as scales and drills, sound is not so important, as for subtle performance practice you will need an acoustic piano eventually at some point.
If you have been playing for five years, you have enough sensibility your self to try out several instruments and judge for yourself if the overal feeling and response is to your liking. Try to go to a shop and try different models to see if the price difference is worthy (for you).
Second hand digital pianos also suffer from heavy use, so always try it before commiting.
Regarding features, if your purpose is to study piano, put your money on the best responsive keyboard you can afford, forget about multiple sounds, effects, integrated sequencers and song recorders, etc.
Comment: Thanks. Of course I will try it, especially second hand piano. I am aware that the touch is really important. As I want to improve also my hearing I want something that's sound like a real piano. I want a piano that last long, I don't want to change in two years to get a better one. By having a lot of "toys" like effects and multiple sounds I think I will spend even more time to play with and improve my composition skill. Anyway thanks for the advice I will focus on trying a lot of piano to find the good one :)

Choose a digital piano


Do you always play the melody louder than the accompaniment, unless specified?

Question: The moonlight sonata 1st movement by Beethoven, for example, has a melody on top with an accompaniment with the left AND right hand (starts at measure 5). People usually say that you play the melody with your pinky louder than the accompaniment. But why? In the sheet music, that has not been specified, but if you were to specify it, you would have two dynamic markings for one staff (accompaniment right hand soft, and melody right hand loud). Is this always the case, that you play the melody louder than the accompaniment, unless specified?
Comment: This presumes that one can always unambiguously identify the melody in a piece, which is not the case.
Comment: @epanoui and tommsch, answers in the comments are highly discouraged. Epanoui, that is a great start, Consider expanding that into an answer.
Comment: As requested, I've moved my comments into an answer instead.  I didn't do this earlier because I didn't consider my "answer" that substantial.
Answer: This is not generally easy to answer since "louder" is ill-defined anyway: on a piano, the lower notes have more string mass behind them, and an accompaniment more often than not has a whole number of notes being held in contrast to a single treble line.
Added to that, the piano is a percussive instrument.  Historic predecessors like the cembalo (at least single-manual variants) were not even capable of producing different loudness for melody and accompaniment.
So the important thing is that the melody can be discerned rather than it being stronger in volume.  A whole lot is already accomplished by it being usually on top, making at least its overtones occupy a comparatively uncontested frequency space.  A lot can be achieved using articulation: this is a tool that is a bit underrepresented in the piano player's conscious toolbox since the release is somewhat underrepresented in importance compared to the attack, however it still is important for creating coherent melodic lines that stick together in defiance of accompaniment.
Then for orchestration, one can give the melodic lines signature sounds, instruments that don't have all that many overtones but rather particular ones, like an oboe.  Those tend to be comparatively robust to follow even against a not-all-that-quiet orchestral backdrop.
Basically human hearing has a lot of features it is able to lock onto, and loudness is one of the more reliable and less subtle ones.  But relying on it solely gets old eventually.  It's good if you keep other tools in your box.
Answer: Yes, you play the melody louder than the accompaniment, unless specified.
Questions regarding the relationship between melody and accompaniment are easily answered, if one thinks about, what melody and accompaniment are in reality, namely different voices. In the case of the moonlight sonata we have most of the time 3 voices: Melody, Middle voice (the running triplets), and base.
Think about the piece played by an orchestra. The Middle voice could be the strings, the base will be cello and contrabase, the upper voice could be some wood-instruments.
Now it is immediate clear, that the strings will not play louder then the wood, because this would sound very strange.
The dynamic marking in the scores thus tells us the loudness of all instruments played together, not the dynamic of each instrument.
Answer: By convention, usually yes. By necessity, no.
Music written as melody/accompaniment is generally intended to follow that approach and is usually performed that way.
There are (of course) exceptions. In much Baroque counterpoint the listener can focus on one or more voices at a time or can listen to it as a whole.
Also, there's no rule against a composer moving melodies from the background to take center stage, or moving a prominent melody into the backdrop.
Many Classical pieces do this de facto by presenting accompaniment (which can be perceived as melody) before the intended melody begins. Moonlight Sonata, in fact, has this trait.


Metric for subset of $\mathbb{R}^n$

Question: Consider the collection of points in $\mathbb{R}^n$ whose coordinates are all strictly positive. I want to think of this subset as a Riemannian manifold. Does anyone happen to know what the Reimannian metric would be?
Comment: I am not sure to understand the question. Isn't the induced Riemannian metric fine ?
Answer: The set $P = \{(x_1, \dots, x_n) \in \mathbb{R}^n \mid x_1, \dots, x_n > 0\}$ is open and is therefore an open submanifold of $\mathbb{R}^n$.
The restriction of a Riemannian metric to an open submanifold is again a Riemannian metric. Therefore $P$ carries a natural Riemannian metric given by $g|_P$ where $g = dx^1\otimes dx^1 + \dots + dx^n\otimes dx^n$ is the usual Riemannian metric on $\mathbb{R}^n$.

Metric for subset of $\mathbb{R}^n$


How do I send mail using mailchimp key and id in ASP.NET C#

Question: i want send mail (text and document) using mailchimp in asp.net c# for this. I download dll file (v3.0 API) from nuget and generate key and Id form mailchimp website.I Also Add API key in webconfig file now i can't  implement code for send mail using mailchimp in  cs page in asp.net c#..
<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MailChimp.Net;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
   MailChimpManager manager = new MailChimpManager("string for API Key");

}
}
</code>
Answer: For any tool implementation/integration one should refer the original documentation of that tool.
However you can refer this github project for reference but I am not sure whether it will completely fulfill your requirement or not.
https://github.com/danesparza/MailChimp.NET
Comment: I can't understand their code.  mandrill is  use full for send mail


Trying to get a "Is between" date filter to work... it is returning an offset by + 1 days.

Question: Please see my website to see what i'm talking about: http://apollo.tbc.iit.edu/~spaceweather/sw_test/?q=download-cases-data#
Ive found some examples and posts on how to do this but even after following them i'm still having issues.
I'm trying to filter the results shown in a table. I want the dates in between the two specified dates a user might put in.
When I select 05/24/2013-05/26/2013 I get an offset of 05/25/2013-05/27/2013 for the results. Can anyone help with this?  I'm storing the date as a Unix time stamp.
Thank you for your help!
(*Note my website has been updated according to the suggestion below by @adem .)
Comment: It might be helpful if someone can help me understand how i can begin to go through the code for the date/time module or views filters to understand where this issue is arising.  I suspect there is a difference between the filter and how it actually uses a Unix time stamp (epoch) but I have a hard time getting started debugging this.
Comment: The dates are stored in the database table as epochs and are converted using DateTime::createFromFormat('Y-z',...) in a php script i use to first insert the data into the database.   Then I use the data module to pull that data into drupal.  I can then access this table from the views interface.
Answer: The filter type must be "single filter",
operator must be "is between", as demonstrated in this screenshot:
Comment: I made this change. It is nice they have this option like this.  Much easier than doing the two filters.  Anyway it still has the strange offset issue.  When i'm selecting 5/24-5/26 it gives me 5/25-5/27.  Is this some kind of issue with time zones or something weird? Please [click here](http://apollo.tbc.iit.edu/~spaceweather/sw_test/?q=download-cases-data&fileDate[min][date]=Friday%2C%20May%2024%2C%202013&fileDate[max][date]=Sunday%2C%20May%2026%2C%202013&fileRec=All&items_per_page=100&ℴ=fileDate&sort=asc) to see the change
Answer: I figured out my own issue, which as with most quirky issues like this end up being buried in the details that other users wont know right away.
When I put these dates into my database I used an offset timezone for "America/Chicago".  In the on the Drupal side it was displaying the time in UTC which happens to be forward 5 hours from CST time.
I went to edit the field I created for these dates and changed the timezone from UTC to "America/Chicago" and it fixed the issue. Everything filters nicely now.
Here is a screen shot of where i found this option to change things.   I hope this helps others who might see an unexpected offset in their days.    Always make sure your timezones are correct to what youre expecting!


Gradient of distance vector length

Question: Suppose that there is a surface described by:
$\phi(x,y,z)=c$
And suppose that there is a fixed point A:
$\vec{r_A}=(x_A,y_A,z_A)$
Let $\vec r$ be position vector of any point on the surface so that:
$R=|\vec r-\vec r_A|$
Show that $\nabla R$ is a unit vector whose direction is along $\vec r-\vec r_A$
I tried to write $z=f(x,y)$ and then calculate what is $\nabla R$ but I got that it has no $z$ component which leads to a contradiction...
Comment: There is something wrong here. As defined in your question, $R$ is a function on your surface (let's call it $M$). As such, it can only be differentiated along $M$, and it's gradient (wrt M) is a tangent vector of $M$.However,  $\vec {r}-\vec r_A$ is, in general, not tangent to $M$.
Answer: By denoting $\vec r = (x,y,z)$ you can write $R = \sqrt{(x-x_A)^2+(y-y_A)^2+(z-z_A)^2}$. Then as $\nabla = (\frac{d}{dx},\frac{d}{dy},\frac{d}{dz})$ I will just do the calculation for the $x$-coordinate, as it is completely analogous for $y,z$:
$\frac{dR}{dx} = (\frac{1}{2}) R^{-1} 2 (x-x_A) = \frac{x-x_A}{R}$
And by putting all coordinates together that gives you:
$\nabla R = \frac{1}{R} (\vec r - \vec r_a) $ which is just $\vec r - \vec r_a$ divided by its norm and has therefore unit length.
Answer: $$R=|\vec{r}-\vec{r}_a|=|(x-x_a)\mathbf{i}+(y-y_a)\mathbf{j}+(z-z_a)\mathbf{k}|=\sqrt{(x-x_a)^2+(y-y_a)^2+(z-z_a)^2}$$
Now take $\nabla R$

Gradient of distance vector length


Use path alias as contextual filter

Question: I have nodes in Drupal for News Articles that generates this automatic URL alias.

I also have a view for News nodes.

This is the data.

The problem is that I can't use Content: Path (url) or Content: Path (Path) as contextual filter.
sync/newslist/1234, where 1234 is node ID, works. I would like to pass the path or the URL to the contextual filter, so that sync/newslist/world-first-chart-alerts-non-artists will return that node.
Comment: This is not a contextual filter issue. The problem is you never reach the View via the path alias because it doesn't match. You could write your own path processor for the partial match or try a contrib module like https://www.drupal.org/project/subpathauto
Answer: You can for example create a custom ViewsArgumentValidator and transform the given alias to the Node ID.
<code><?php

namespace Drupal\my_module\Plugin\views\argument_validator;

use Drupal\path_alias\AliasManagerInterface;
use Drupal\views\Plugin\views\argument_validator\ArgumentValidatorPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Validates whether an alias is a valid node alias and transform it to the nid.
 *
 * @ViewsArgumentValidator(
 *   id = "node_alias",
 *   title = @Translation("Node ID by alias")
 * )
 */
class NodeAlias extends ArgumentValidatorPluginBase {

  /**
   * The alias manager.
   *
   * @var \Drupal\path_alias\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AliasManagerInterface $alias_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->aliasManager = $alias_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('path_alias.manager'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function validateArgument($argument) {
    // Prepend slash.
    $argument = '/' . ltrim($argument, '/');
    $path = $this->aliasManager->getPathByAlias($argument);

    if (preg_match('/node\/(\d+)/', $path, $matches)) {
      $this->argument->argument = $matches[1];
      return TRUE;
    }
    return FALSE;
  }

}
</code>
In the validateArgument function we are checking if an internal path for a node can be found with that alias and transform the given argument to the corresponding Node ID.
Add this file named NodeAlias.php to you custom module in src/Plugin/views/argument_validator directory and clear the cache.
After that, you can use the Content: Nid contextual filter and select in the "When the filter value is in the URL or a default is provided" section the new Validator Node ID by alias.

Use path alias as contextual filter


Uniqueness of memoryless property

Question: How does one prove that the unique continuous distribution with the memoryless property is the exponential distribution? i.e. Suppose we know that a continuous random variable $X$ satisfies
$$P\{X > t+s \mid X > s \} = P\{X > t \}$$
Then how do we show that $X \sim \text{Exponential}(\lambda)$ for some $\lambda > 0$?
Thanks.
Comment: This is equivalent to $P(X>t+s)=P(X>t)P(X>s)$ which tells you that $P(X>t)$ is a decaying exponential.
Comment: I always find it irritating when someone writes $\text{Exponential}(\lambda)$ as if that were not at best ambiguous.  Sometimes $X\sim\text{Exponential}(\lambda)$ means $\Pr(X>x) = e^{-\lambda x}$ for $x\ge0$ (so the intensity is $\lambda$ and the expected value is $1/\lambda$) and sometimes it means $\Pr(X>x) = e^{-x/\lambda}$ for $x\ge0$ (so the intensity is $1/\lambda$ and the expected value is $\lambda$). $\qquad$
Comment: @Michael I shared your sentiment initially, but it looks like today - esp. in modern works - $\lambda$ is predominantly/exclusively referring to rate/intensity while $\beta$ is to denote the mean - but it might be field/application dependent.
Comment: https://math.stackexchange.com/questions/1801830/on-the-proof-that-every-positive-continuous-random-variable-with-the-memoryless
Answer: Let $g(t) = \Pr(X>t)$. Then memoryless tells us that $g(t+s)=g(t)g(s)$. Consequently $g(t_1+t_2+t_3)=g((t_1+t_2)+t_3) = g(t_1+t_2) g(t_3) = g(t_1) g(t_2) g(t_3)$, and it should become clear why $g(t_1+\cdots+t_n)=g(t_1)\cdots g(t_n)$ for every finite number $n$.  Thus
$$
g(n) = g(1+\cdots+1) = g(1)\cdots g(1) = (g(1))^n,
$$
so $g$ is an exponential function of $n$ as long as $n$ is a positive integer.  So what about non-integers?
$$
\left(g\left(\frac 1 8 \right)\right)^8 = g\left(\frac 1 8\right)\cdots g\left(\frac 1 8\right) = g\left(\frac 1 8 + \cdots + \frac 1 8 \right) = g(1)
$$
so
$$
g(1)^{1/8} = g\left(\frac 1 8 \right)
$$
and it becomes clear why $g(t)=g(1)^t$ if $t=\left\{1\text{ over a positive integer}\right\}$. Next let's try $11/8$:
\begin{align}
g\left(\frac{11}8\right) & = g\left( \frac 1 8 + \cdots + \frac 1 8 \right) \\[10pt]
& = \left(g\left(\frac 1 8 \right)\right)^{11} & & \text{because of what was shown about integers above} \\[10pt]
& = \left( g(1)^{1/8} \right)^{11} & & \text{because of what was shown about $1/8$ above} \\[10pt]
& = (g(1))^{11/8},
\end{align}
so $g(t)$ behaves like an exponential function with base $g(1)$ when $t$ is a positive rational number.
Finally, what about irrational numbers $t$?  Notice that $g(t) = \Pr(X>t)$ is squeezed between $\Pr(X>a)$ for all positive rational numbers $a$ that are $>t$ and $\Pr(X>b)$ for all positive rational numbers $b$ that are $<t$.  And also $g(1)^t$ is squeezed between all numbers $g(1)^a$ for rational numbers $a$ that are $>t$ and all numbers $g(1)^b$ for rational numbers $b$ that are $<t$.  One can deduce then that $g(t)$ is still equal to $g(1)^t$.
Hence we have
$$
g(t) = g(1)^t \text{ for all real }t\ge0.
$$

Uniqueness of memoryless property


How to turn the subclass of all epimorphisms of a category, into a category?

Question: Here is how I thought about it:

Suppose $\mathcal{C}$ is a category and $\mathcal{E}$ is the subclass of all epimorphisms of $\mathcal{C}$. I am thinking to a subcategory of $\mathcal{C}$, which has all of epimorphisms as its objects and all commuting squares as its morphisms (just like the construction of arrow category).

Is everything fine with such a definition?
Comment: This isn't a subcategory of $C$, it's a subcategory of the arrow category of $C$.
Comment: In this case I would not call $\mathcal{E}$ a subcategory of $\mathcal{C}$.
Comment: Of course, you could also form the non-full subcategory of $\mathcal{C}$ whose morphisms are the epimorphisms. This makes sense because the composite of two epimorphisms is another epimorphism.
Answer: The definition is fine in the sense that it gives a well defined mathematical object. Simply put, it is the full subcategory of the category of arrows on $\mathcal {C}$ spanned by the epimorphisms in $\mathcal {C}$. The same will work with any chosen subclass of the arrows on $\mathcal {C}$. Whether or not this is a sensible construction to make depends on the reason why you want to turn the epimorphisms into objects in a category.
Notice that the resulting category is not a subcategory of $\mathcal {C}$.


ROC curves: can a cut-point (cut-off) be "useful", or is it a term reserved to parameters only?

Question: This is a semantic question:
When analyzing Receiver Operating Characteric (ROC) curves, we talk about the "usefulness" of a parameter based on its Area Under the Curve (AUC). "Useful" here refers to the discriminative utility of the entire parameter and not just any threshold selected on the spectrum. Let's say I proceeded to select a threshold (cut-point, cut-off) with sensitivity and specificity both >80%. I expect this to be a "useful" threshold in its own sense. Should I be using a different term to describe its utility for me in order to avoid confusion?
Answer: "Usefulness" is not a scientific word
The "usefulness" of a parameter is a pretty subjective quality and not very useful (sic) on its own. Just as words like "best" or "bad", in scientific writing it should never be employed without stating the reason that makes you think it is useful (such as the AUC, etc.)
In any case, "useful" doesn't have a reserved meaning, and should always be optional.
You can apply "useful" to anything you want
Similarly you should never associate "useful" to a threshold without stating why you think the threshold is useful (sensitivity, specificity, accuracy etc). However, if it suits you and helps you convey a message, you should feel free to qualify a threshold of useful, keeping in mind that it doesn't provide any additional information to the reader.


C# MethodInfo Invoke() with JSON args

Question: the Invoke() function on a MethodInfo object accepts parameters as an object[]. I want to be able to send a JSON encoded string instead. Is there any way to do this?
The code which i am basing mine of comes from this MSDN page
....
object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);

//args in this case is an object[]. any way to pass a string?
return mi.Invoke(wsvcClass, args);

I am aware that Newtonsoft provides a way to deserialize strings but can it do so into an object[]? or is there another way to do this?
Answer: The method signature you are looking at takes an Object[] representing all parameters in your method.  For example:
public void DoStuff(string x, string y, int b);

Could be called like this:
methodInfo.Invoke(wscvClass, new object[] { "x", "y string", 500 });

So in your case you should be able to call Invoke using:
string jsonEncodedString = "{ }"; // whatever you need to do to get this value
mi.Invoke(wsvcClass, new object[] { jsonEncodedString });

MethodInfo MSDN Link
Comment: Theres something about `new[]{...}` that doesnt seem to sit well. Even though the json fields map directly to the parameter names, it gives an error saying 'mismatched parameters' or something like that. luckily, there is a way to map these parameter names as per [here](https://stackoverflow.com/questions/13071805/dynamic-invoke-of-a-method-using-named-parameters)
Comment: Yeah sorry, I was typing it using implicitly typed arrays.  If you specify new object[] that should do the trick.  Updated answer

C# MethodInfo Invoke() with JSON args


Lattice distributed random variable and its characteristic function

Question: I'm working on the following problem and I''m stuck at the begining.
Let $X$ be a lattice distributed random variable, i.e $\exists\, a, b \in \mathbb{R}$ s.t.
$$P[X \in a + b\mathbb{Z}]=1$$
Let $\varphi$ be the characterstic function of $X$.
Show that if $X$ is lattice - distributed, then there exists $u\neq 0$ such that
$$\lvert\varphi(u)\rvert = 1$$
I first noticed that: $\lvert e^{itX}\rvert = 1$
Which could mean that:
$\lvert\varphi(u)\rvert = \lvert e^{itX}\rvert = 1$
Then:
$\varphi(u) = E[e^{iuX}] = e^{itX}$ for some $t\in\mathbb{R}$.
Any help would be appreciated.
Answer: If $b=0$ the any $u$ will do. Suppose $b \neq 0$. Take $u=2\pi /b$. We have $\phi (u)=Ee^{(2i\pi/b) X}=\sum e^{2i \pi (\frac  a b+n)} P(X=a+b n)=e^{2i \pi (\frac  a b)}$ so $|\phi (u)|=1$.


Filter a view by a field on a referenced entity

Question: Sorry to be yet another question about entry reference relationships in views, but I can't find the answer in pre-existing questions.
Given:

the content type "page" has an entity reference field "artref" that references multiple nodes of the content type "article"
the content type "article" has a boolean field "fishy"

How do I create a view that shows all pages which reference at least one article where fishy is checked.
I understand that here are 4 relevant settings:

the basic entity bundle (pages or articles) selected for the view
the relationship type ("content referenced from" or "content using")
"require this relationship" setting
Aggregation, especially if "distinct" is a possibility

All advice much appreciated
Answer: I figured it out. Configure in this sequence:

Show: "content" of type "page"
Relationships: "Content referenced from art_ref"
Use Aggregation: Yes
Add filter criteria: fishy, Aggregation: "group results together", relationship: "art_ref:content", operator: "is equal to" "1"
Answer:
Create new content type,for example, "Article_1",having "fishy"
field of boolean type.
Create new content type "Page_1",having entity reference field
"artref" to "Article_1" content type. Values - unlimited.
Create new View with filter criteria Content:Type="Page_1".
In view "advanced" section add Relationship:"Content entity
referenced(not referencing) from field_artref". "Require this
relationship" you may live unchecked.
Add new filter criteria is based on "fishy" field = "Yes", for
example.("Yes" is "On value" and "No" is a "Off value" for boolean
"fishy" field).
Set relationship for this filter criteria to "Content entity
referenced from field_artref".
In "advanced" section open "Query settings:settings" and set to
checked "Distinct" checkbox.
Comment: Doesn't work for me, on simplytest.me with D8.0.1.
Distinct fails to remove the duplicates (repeated page listings in the view results for pages that reference more than one fishy article).
Comment: Yes, I've just checked up. Distinct really doesn't work. (I meant D7 in my previous answer). Well,just turn on aggregation in advanced section. And then click aggregation link near FIshy filter criteria and choose somethin like "count distinct" from drop down box.


SignalR Hub-2-Hub Communication with SQL Backplane in ASP.NET Owin

Question: I have an ASP.NET Owin Web Api which is load balanced, which means there are multiple instances of it which don´t know each other. The web api hosts a SignalR hub with an SQL Server Backplane (for synchronising between instances), so clients can exchange messages regardless of which instance of the web api they are connected to. Everything working so far.
Client session data is stored in the db. The web api needs this info for processing requests for the client. Because it would be too slow to read the session data from the db for every client request, the web api is reading it only once (on first request from the client session) and caching it in-memory. This also works across multiple instances of the web api as every instance is holding it´s own session data cache.
But now the clients should be allowed to change for example the language, which results in an updated language in the session data stored in the db. The web api instance which processes the "change-language"-request of course can react to the changed session data and clear the session from it´s cache, which will lead to a reread of the session data from the db on the next client request. But the other web api instances don´t know about the session data change, their caches now hold outdated session data.
The web api instance which processes the "change-language"-request would somehow need to notify the other instances to drop their cache for session xyz. Unfortunately the instances don´t know each other, but all instances host SignalR hubs which are synchronised through the SingalR SQL server backplane.
Unfortunately a SignalR hub cannot directly send and receive messages. A HubConnection (client) is needed to do that. So the idea is when every web api instance is connecting to it´s own SignalR hub, it would be able to send messages to itself, which are then spread out to the other instances via the SQL server backplane synchronisation. But a HubConnection can only be established with an URL (http://host:port/signalr) but the web api instance doesn´t know it´s own base url.
So finally my question is:
Is there any way to establish a HubConnection to a hub running in the same process without providing an URL (I have access to the hub object)?
If not, is there any way for a SignalR hub to spread out messages and listen to messages through the backplane without a client (hub-2-hub communication)?
If not what else could I do to notify other instances of my load balanced web api and advice them to drop their session data cache?
Comment: `a SignalR hub cannot directly send and receive messages.`??? Quite the opposite, and all examples show just that, eg [How to call client methods from the Hub class](https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-server#how-to-call-client-methods-from-the-hub-class)
Comment: What's the actual question? What do you mean by `hub-2-hub communication` ? Are you trying to use SignalR to do something it's not meant to do perhaps? Its job is to send messages to clients, not replace Web API or other HTTP APIs
Comment: @PanagiotisKanavos: but I need a hub to send a message to another hub which is synchronized through the backplane, not to a client. I explained this quite clearly imo. I also asked for alternate ways if this isn´t possible or isn´t meant to be used like that.
Comment: Which is not what SignalR is about.  The question isn't clear at all, there's a lot of text that essentially asks `Can SignalR be used to send notifications between hubs in a farm?` and the answer is `No, that's not what it's for`. The *real* question though seems to have nothing at all to do with SignalR - how to update client session information, or even how to *fix* the database performance issues
Comment: If you fix the *real* issue you won't have to use in-memory session only, because that's what you do. If the session is loaded only once, essentially it's in-mem only. What does slow mean in this case? Why is session loading slow? Is there too much data? Missing indexes? Underpowered database server?
Comment: If you have such high traffic (*how* much?) that a regular database table is an issue, you can use an in-memory table in SQL Server or a Redis cache to store the session. What you try to do is emulate a distributed Redis cache. Why not use an *actual* Redis cache? Trying to get the web servers to act like Cache nodes is non-trivial. Microsoft tried this for a long time with AppFabric Cache before abandoning it for Redis.
Comment: Again, what's the *real* problem though? Quite often "big data" or "high traffic" problems are caused by bugs, misconfiguration or simply inadequate hardware. Fixing the real problem is easier and cheaper than trying to cover it up
Comment: For example, what if *two* changes are made to the same setting? Even if SignalR acted like eg MSMQ and sent messages between nodes, how would that solve the concurrency issue? SignalR *depends* on a backplane to solve that issue, it can't do it itself. You're asking SignalR not just to send messages between hubs, you're asking it to become Redis
Comment: The [Distributes caching in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-5.0#distributed-ncache-cache) article mentions several different ways to store session state: a database, Redis or NCache. Have you tried [NCache](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-5.0#distributed-ncache-cache)?
Comment: The IDistributedCache interface pointed me into the right direction, thanks.
Answer: Solved through distributed caching (IDistributedCache), as mentioned by Panagiotis Kanavos in the comments.


When writing a melody on top of a riff, is there a rule for what types of notes you use?

Question: When writing a melody on top of a riff, is there a rule for what types of notes you use?
For example, if your riff has goes A, B, C continuously, do the notes in the melody have to be certain notes with each note of the riff, or can they be anything?
Comment: As it stands, I think the question is too vague in content to be answered usefully. Basically, no rules apply, so any melody that sounds good will be deemed to fit. Don't use rules; use ears!
Answer: Rather than directly choosing melody notes based on the notes in your riff, it would be more common to consider what tonality (or tonalities) your riff could suggest, and then write a melody line that has the same tonality.
For example, a riff that goes A, B, C continuously could (depending on its phrasing) suggest the key of A minor, so you could take notes from the A minor scale as your starting point (though as Neil Meyer points out in his comment, that doesn't mean you're restricted to that set of notes!). Alternatively, you could work in a blues tonality rooted on A. Another possibility might be C major.
However, there's no one rule, and there are all sorts of possibilities. If the riff was slower, you could choose notes from G major over the A and B, and notes from C minor over the C. Or you could play a melody that sometimes followed the phrasing of the riff but a perfect fifth higher, creating a kind of 'oriental' sound... or just muck about and try things and see what sounds good. usually if you're composing, you have the time to come up with something interesting by trial and error!
Comment: Even if you are operating under a certain key you can still have chromaticism and other non-chordal notes that may fit outside the key, not to mention the possibility of modulations in your melodies.
Comment: @NeilMeyer Absolutely - edited that first point in. Keys (and other tonalities that aren't best described as 'keys') can be taken as landmarks to navigate by, rather than roads you mustn't stray from.
Answer: The number of rules is so huge, that you can actually justify absolutely any sound on top of any other sound. The only rule concerning a single sound that still stands is "avoid notes which are one half tone above the base note" (for A avoid A#, with B avoid C and with C avoid C#). But even this last rule can have exceptions - note that dissonant sound is not an "error".
Most of rules for "good sounding" harmonies depend on context which is only present in imagination of your listeners. Exactly the same chord can sound strange and dissonant or quite tame, depending on the current melody.
Your riff (A B C B etc...) will probably evoke the feeling of A minor. Unless bass plays F or D (then people will imagine F lydian or D dorian). The most consonant notes for this setup would be A C D E G (note that C will clash with B, so you might want to be slightly careful here).
Comment: Consider a 7b9 chord. The extra note *is* one half tone above the base note.
Comment: @Tim: This is why care must be taken when handling dissonant chords. Not every voicing will sound "good".


Which tables should be emptied when clearing database-stored cache manually?

Question: Prior to D8 to clear cache manually one could truncate all tables beginning with cache_.
In Drupal 8 there are still tables starting with cache_, but there's also a cachetags table.
Is the advice in D8 still to truncate cache_* if you need to clear cache manually? Is it safe/required/recommended to truncate the cachetags table along with the cache_* tables?
I'm aware there may be contrib modules doing things differently, I'm mostly interested in what core does, and what's considered "best practice" for Drupal 8 in general.
Comment: ... which is https://api.drupal.org/api/drupal/core!includes!common.inc/function/drupal_flush_all_caches/8.2.x
Comment: You can just look at what clear all cache button does.
Comment: All the cache tables are safe for truncating, didn't entirely remove them though.
Answer: In drupal 8 if you are looking for the safe tables that needs to be cleared manually then clear the tables starting with cache_   and also truncate the cachetags table too.
If you are using drush then use this command for clear cache-
drush cache-rebuild
Answer: According to this article cachetags are set when cache objects are being stored, so it should be safe to truncate this table also. Cachetags identify cache objects and you can get all related objects at once.
Comment: I tested and the table can be truncated without problems (or only with the potencial performance problem). It is recreated when the entity is loaded but... I don't know why if you delete a entity instance the tags saved in cachetags are already in the table.

I thing that it has to be removed.
Comment: I assume data from cachetags table are removen on cron run and what you see after entity removal are just leftovers
Answer: You could do this for a one-liner:
drush sqlq "TRUNCATE cache_default;TRUNCATE cache_bootstrap;TRUNCATE cache_container;TRUNCATE cache_discovery;TRUNCATE cache_data;" -l <uri> --no-interaction

Add as many with cache_ prefix as you would like.
Answer: This is very handy. Replace dbname as needed:
DB_NAME="dbname"

mysql -uroot -proot --execute="SELECT concat('TRUNCATE TABLE ', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '${DB_NAME}' AND TABLE_NAME LIKE '%cache%'" | sed 1d | mysql -uroot -proot ${DB_NAME};


Specifying contrasts using afex

Question: I would like to understand how to specify a contrast in a follow-up analysis using the afex package. Below I included code from the documentation and explain why I do not follow all steps here.
Edit: I was doubting whether to post here or on stackoverflow. I decided to post here because I am also interested in understanding differences in output for different tests (aside from understanding how to use R-code to specify contrasts in afex).
Code from the afex documentation:
    ########################### ## 2: Follow-up Analysis ## ###########################
    # use data as above
    data(obk.long, package = "afex")
    # 1. obtain afex_aov object:
    a1 <- aov_ez("id", "value",
                 obk.long,
                 between = c("treatment", "gender"),
                 within = c("phase", "hour"),
                 observed = "gender")
    # 2. obtain reference grid object (default is uses univariate model):
    r1 <- emmeans(a1, ~treatment +phase, model = "multivariate")
    r1
    # treatment phase   emmean        SE df lower.CL upper.CL
    # control   fup   4.333333 0.5511982 10 3.105187 5.561479
    # A         fup   7.250000 0.6038074 10 5.904633 8.595367
    # B         fup   7.291667 0.4611655 10 6.264126 8.319207
    # control   post  4.083333 0.6277716 10 2.684571 5.482096
    # A         post  6.500000 0.6876894 10 4.967733 8.032267
    # B         post  6.625000 0.5252314 10 5.454711 7.795289
    # control   pre   4.250000 0.7660323 10 2.543174 5.956826
    # A         pre   5.000000 0.8391464 10 3.130265 6.869735
    # B         pre   4.166667 0.6409086 10 2.738633 5.594700
    #
    # Results are averaged over the levels of: gender, hour
    # Confidence level used: 0.95

Based on this reference grid, I would specify the contrast A_B_pre (A vs. B, pretest) as follows: c(rep(0, 6), 0, -1, 1). However, the documentation specifies the same contrast as A_B_pre = c(0, -1, 1, rep(0, 6)) (which to me seems to compare A vs. B in the follow-up treatment):
    # 3. create list of contrasts on the reference grid:
    c1 <- list( A_B_pre = c(0, -1, 1, rep(0, 6)),
                # A versus B for pretest
                A_B_comb = c(0, 0, 0, 0, -0.5, 0.5, 0, -0.5, 0.5),
                # A vs. B for post and follow-up combined
                effect_post = c(0, 0, 0, -1, 0.5, 0.5, 0, 0, 0),
                # control versus A&B post
                effect_fup = c(0, 0, 0, 0, 0, 0, -1, 0.5, 0.5),
                # control versus A&B follow-up
                effect_comb = c(0, 0, 0, -0.5, 0.25, 0.25, -0.5, 0.25, 0.25)
                # control versus A&B combined
    )
    # 4. test contrasts on reference grid:
    contrast(r1, c1)
    # contrast       estimate        SE df t.ratio p.value
    # A_B_pre      0.04166667 0.7597743 10   0.055  0.9573
    # A_B_comb    -0.35416667 0.8327863 10  -0.425  0.6796
    # effect_post  2.47916667 0.7624260 10   3.252  0.0087
    # effect_fup   0.33333333 0.9303431 10   0.358  0.7276
    # effect_comb  1.40625000 0.7337579 10   1.917  0.0843
    #
    # Results are averaged over the levels of: gender, hour

For the comparison of treatment A vs. B in the phase pre, the estimate of the difference (based on the contrast from the documentation) is 0.04166667. However, when I calculate that difference, I obtain 0.8571429: 1)
    mean(obk.long[obk.long$treatment=="A" & obk.long$phase=="pre",]$value, na.rm=TRUE) -
    mean(obk.long[obk.long$treatment=="B" & obk.long$phase=="pre",]$value, na.rm=TRUE)
    # [1] 0.8571429

As I mentioned above, to me it seems that the contrast from the documentation compares A vs. B in the follow-up treatment. Indeed, when I manually calculate this comparison in the follow-up treatment, I come closer to the output from afex, although I am still far away from an exact match:
    mean(obk.long[obk.long$treatment=="A" & obk.long$phase=="fup",]$value, na.rm=TRUE) -
            mean(obk.long[obk.long$treatment=="B" & obk.long$phase=="fup",]$value, na.rm=TRUE)
    #[1] -0.03571429

    t.test(obk.long[obk.long$treatment=="A" & obk.long$phase=="fup",]$value,
           obk.long[obk.long$treatment=="B" & obk.long$phase=="fup",]$value)
    #p-value = 0.9484

1)
Edit 2: When obtaining all pairwise comparisons (i.e., without using the contrasts specified in the documentation, I obtain 0.83333333, which comes relatively close to 0.8571429 (differences likely arise because I do not control for gender and hour here, see also below):
emmeans(a1, c("treatment", "phase"), contr = "pairwise", model = "multivariate")
#...
#$contrasts
#contrast                    estimate        SE   df t.ratio p.value
#...
#A,pre - B,pre               0.83333333 1.0559027 10   0.789  0.9946

Additional thoughts / bonus question:
Perhaps the difference arises because in the contrast for the afex package, hour and gender are controlled for? Usually I would regress the dependent variable (value) on these variables (hour and gender) and then use the residuals in the next analysis (i.e.,  the t-test), but in this case I receive only 16 residuals (16 residuals for each level of hour) instead of 240 residuals (1 for each observation). Is it possible to control for hour and gender in the t.test above?
    a2 <- aov_ez("id", "value",
                 obk.long,
                 between = c("gender"),
                 within = c("hour"),
                 observed = "gender")
    residuals(a2$lm)
    # X1         X2          X3          X4          X5
    # 1  -3.4583333 -3.4583333 -3.29166667 -2.95833333 -2.87500000
    # 2  -2.1250000 -2.1250000 -2.29166667 -1.95833333 -2.54166667
    # 3  -0.1250000 -0.1250000  0.04166667  0.37500000  0.45833333
    # 4  -0.8333333 -1.5416667 -1.37500000 -1.16666667 -0.70833333
    # 5  -0.1666667 -0.2083333  0.29166667 -0.83333333 -1.37500000
    # 6   2.8750000  3.2083333  2.37500000  2.70833333  2.79166667
    # 7   1.2083333  1.2083333  1.37500000  1.70833333  1.79166667
    # 8  -1.1666667 -0.5416667  0.29166667 -0.83333333 -0.04166667
    # 9  -0.5000000 -0.8750000 -0.70833333 -0.50000000 -1.37500000
    # 10  0.5416667  0.5416667 -0.29166667  0.04166667  1.45833333
    # 11 -1.1250000 -1.4583333 -0.62500000 -1.62500000 -1.20833333
    # 12  2.2083333  2.2083333  2.70833333  1.70833333  0.12500000
    # 13  0.8333333  1.1250000  0.29166667  3.16666667  2.29166667
    # 14 -0.1666667  0.1250000 -0.37500000 -1.50000000 -2.04166667
    # 15  0.5000000  0.1250000 -0.37500000  0.83333333  1.62500000
    # 16  1.5000000  1.7916667  1.95833333  0.83333333  1.62500000

Comment: What documentation do you refer to??? The contrast coefficients are always applied to the means as ordered in the grid. So your first impression is right.
Comment: Second, `emmeans()` computes predictions from the model, and those may not be the same as ordinary marginal means, as you are seeing happens. Read `vignette("basics", package = "emmeans")`
Comment: @rvl Indeed a mistake in the documentation...
Comment: @rvl: The package documentation in this link (on p. 16/17): https://cran.r-project.org/web/packages/afex/afex.pdf. Ah, that explains the slight difference.
Comment: Suggest reporting this to Henrik. Seems like a documentation blurp, or he'd meant to make phase an ordered factor.
Answer: Thanks a lot for reporting this. It is indeed a mistake in the documentation. This and all the following contrasts were wrong. I guess when I wrote the code the ordering of the factor was different or I just made a stupid error. Sorry for that.
The latest development version on github now does it correctly:
[...]
> r1 <- emmeans(a1, ~treatment +phase, model = "multivariate")
> r1
 treatment phase   emmean        SE df lower.CL upper.CL
 control   fup   4.333333 0.5511982 10 3.105187 5.561479
 A         fup   7.250000 0.6038074 10 5.904633 8.595367
 B         fup   7.291667 0.4611655 10 6.264126 8.319207
 control   post  4.083333 0.6277716 10 2.684571 5.482096
 A         post  6.500000 0.6876894 10 4.967733 8.032267
 B         post  6.625000 0.5252314 10 5.454711 7.795289
 control   pre   4.250000 0.7660323 10 2.543174 5.956826
 A         pre   5.000000 0.8391464 10 3.130265 6.869735
 B         pre   4.166667 0.6409086 10 2.738633 5.594700

Results are averaged over the levels of: gender, hour
Confidence level used: 0.95
> c1 <- list(
+   A_B_pre = c(rep(0, 6), 0, -1, 1),  # A versus B for pretest
+   A_B_comb = c(-0.5, 0.5, 0, -0.5, 0.5, 0, 0, 0, 0), # A vs. B for post and follow-up combined
+   effect_post = c(0, 0, 0, -1, 0.5, 0.5, 0, 0, 0), # control versus A&B post
+   effect_fup = c(-1, 0.5, 0.5, 0, 0, 0, 0, 0, 0), # control versus A&B follow-up
+   effect_comb = c(-0.5, 0.25, 0.25, -0.5, 0.25, 0.25, 0, 0, 0) # control versus A&B combined
+ )
> contrast(r1, c1)
 contrast      estimate        SE df t.ratio p.value
 A_B_pre     -0.8333333 1.0559027 10  -0.789  0.4483
 A_B_comb     2.6666667 0.7962586 10   3.349  0.0074
 effect_post  2.4791667 0.7624260 10   3.252  0.0087
 effect_fup   2.9375000 0.6694279 10   4.388  0.0014
 effect_comb  2.7083333 0.6519868 10   4.154  0.0020

Results are averaged over the levels of: gender, hour

You can install it via: devtools::install_github("singmann/afex@master")
Please let me know if you find other errors.

Specifying contrasts using afex


Representation over a finite field

Question: Are there any two inequivalent and irreducible $F$-representations of a finite group $G$ (where $F$ is a field of positive characteristic) having the same characters?
I can surely find an example in which the representations are not both irreducible, but I thought it would be nice to find an example in which both are irreducible.
Comment: I missed positive characteristic! Sorry about that. The above does not apply.
Comment: Over finite groups, two representations are equivalent if and only if they have the same character
Comment: See [this post](https://math.stackexchange.com/q/608614/81360) for instance
Comment: I suspect that this might not be possible.  The fundamentally "weird" thing about representations over fields of positive characteristic is the existence of reducible but indecomposable representations.  We can't exploit that if we specify that the inequivalent representations must be irreducible.
Answer: No, characters of a collection of irreducible representations are distinct and linearly independent. This is Corollary 9.22 in Isaacs book "Character Theory of Finite Groups".
If you drop the irreducibility assumption then, in characteristic $p$, the sum of $p$ copies of any representation has the zero character. Brauer characters, which take values in the complex field even when the representation is in finite chracteristic,  were introduced (by Brauer) as a means of distinguishing between any pair of non-isomorphic representations.
Comment: Let $F=GF(3)$ and let $G=C_2$. Then an irreducible $F$-representation of $G$ is given by, e.g., the matrix $(1)$ (the trivial representation) and the matrix $(2)$ over $F$. But $2(2)+(1)=(2)$? Where am I wrong?
Comment: I don't think you are wrong. But how does that contradict what I wrote?
Comment: Yep, you're right. I mixed up the linearity of matrices and linearity of characters. Thanks!

Representation over a finite field


GLM modeling binomial proportions with varying trials and probabilities

Question: A collection of coin manufacturers, $m$, each produces a line of coins, the number of which varies by manufacturer (some produce 3 types of coins, others make 7, and so on). Each manufacturer imparts a characteristic bias towards flipping heads on all their coins. Further, manufacturers produce many of the same types of coins, $c$, which have a fixed, unknown bias. We can estimate the impact of coin, $c$, through an external database of coin-specific biases. Lastly, the coins are pressed once each year, $a$, and each pressing of the coins has another unique bias shared across all manufacturers and coins. Each coin is flipped a variable number of times, $n_i$, and the number of heads could be represented as
\begin{align*}
    y_{i,m,c,a} \sim \textrm{Binom}(n_{i}, p_{m,c,a})
\end{align*}
Assuming a large data set of coin-flip trials across an identifiable set of conditions (i.e., year, manufacturer, coin type), I would like to estimate the $m$ biases. Our measured variables are:

number of heads, $y$
number of trials, $n_i$
manufacturer, $m$
coin-specific probabilities (taken from external database), $c$
year, $a$

I would like to estimate $m$ biases and perform a model comparison between nested models that have/don't have manufacturer info in a NHST framework. "Hits" will be manufacturers with large biases. My first thought was to use a generalized linear mixed model (GLMM), yet I'm having trouble figuring out how to specify the model, particularly given the varying number of trials. (For clarification, with simpler designs, I'm familiar with R syntax for using weights when the number of trials varies, function(y/n ~ ., ..., weights = n, ...).)
While I can see a Bayesian formulation for this model,

Please assume a large data set of 100,000 observations and many of these models to fit when proposing an inference strategy
For "historical reasons" (read: this test should look like an extension of an existing testing procedure), I'd like to use maximum likelihood.

I'm an applied scientist, so answers that provide references and code would be most helpful. Would Coull & Agresti  2000 be relevant to my case?
Comment: Is a mixed model necessary? I can't tell this is way to go. I would start with a glm. Maybe something like `glm(cbind(heads, flips) ~ m + year + offset(logit(c_bias)), family = binomial)` in R. I *think* the coin specific biases could be an offset in the model if they can comfortably treated as known from the external database. Welcome to CrossValidated!
Comment: A Bayesian solution will not involve NHST.
Comment: Thanks @JTH--and thanks for the comments. Agreed that your model is a reasonable starting point, and I'm curious to hear others' thoughts on fixed v random here, though I suspect I can make that call myself from the real data.
Comment: A gap in my knowledge that, in part, motivated posting here is
(1) how to specify this model as a multinomial/-variate response of the form `(y_1, y_2, y_3, ..., y_c) ~ m + year + (c_bias_1, c_bias_2, c_bias_3, ..., c_bias_c)`
and
(2) whether inference here would be similar to the model you proposed, akin to reformulating a multinomial as a poisson ('poisson trick')
Answer: A somewhat elegant, but perhaps naive approach, would be to take the coin bias data as trustworthy and known, and include those biases as offsets in a binomial generalized linear model. This automatically handles any imbalances in the number of trials. This also assumes that the effects for year and manufacturer are fixed effects, and that's really in the eye of the modeler. You can code this analysis in R, so I will demonstrate by creating fake data with the additive biases you indicated.
## Create factors for predictors
m <- factor(c("m1", "m2", "m3", "m4", "m5", "m6"))
y <- factor(c("y1", "y2", "y3", "y4", "y5"))
coin <- factor(c("c1", "c2", "c3", "c4"))

## Assume from bias from 1/2 due to coin
c.bias <- c(0, -0.1, 0.1, 0.2)

## Convert to logit scale for logistic glm
logit.c.bias <- qlogis(0.5 + c.bias)

## Create model matrix given predictor data
dat <- expand.grid(m = m, y = y, coin = coin)
X <- model.matrix( ~ m + y + coin, dat)

## Create hypothetical coefficient vector
beta <- c(0, # 1 intercept
          -3, -2, -1, 0, 1, # 5 m coefs, for example
          3, 2, 1, 0, # 4 y coefs, for example
          logit.c.bias[-1]) # 3 coin.biases

lin.pred <- X %*% beta
dat$logit.c.bias <- rep(logit.c.bias, each = 30)

## Sample 500 coin tosses from each coin * manufacturer * year
## For simplicity, I use constant number of trials, but this could be a vector of trials in your problem.
tosses <- 500
heads <- rbinom(nrow(X), tosses, plogis(lin.pred))
dat$heads <- heads

# fit model. Use offset() to include bias. Note, different formula from my comment, I correct typo. f1 correctly recovers parameters.
f1 <- glm(cbind(heads, tosses - heads) ~  m + y + offset(logit.c.bias),
          binomial, dat)

# fit without m
f2 <- update(f1, ~ . - m)

# Test that there is variation in coin bias among manufacturers
anova(f1, f2, test = "LRT")

This analysis could be extended depending on the real problem:

Random effects could be used to model the manufacturer biases

The formula for the random effects version might be
f3 <- glmer(cbind(heads, tosses - heads) ~  (1 | m) + y + offset(logit.c.bias),
          family = binomial, data = dat)

if you use lme4.

A prior distribution for coin biases could be determined from the coin bias database, which is updated based on the experimental data. This would be more realistic than using offsets for coin biases.
Comment: Doesn't *seem* like a multi response problem to me. AFAIK, you've got one outcome, # Heads, which is affected by a few covariates.
Comment: Thanks for the detailed response and providing a simulated data set!

I didn't originally think of the coin bias data as an offset and therefore didn't appreciate that using it as an offset would handle varying numbers of trials, so this was very helpful.

I'm still interested in trying other specifications of this model, as well as playing around with your specification on my data. I'll wait to accept and update here!
Comment: Also-- Any thoughts on treating this as a multiple response model ([described in my comment on the original post](https://stats.stackexchange.com/questions/525936/glm-modeling-binomial-proportions-with-varying-trials-and-probabilities#comment968267_525936)?


Existe alguma forma de arrendondar um valor negativo para zero no VisuAlg?

Question: Gostaria que fosse exibido sempre Vida: 0 no último bloco, mesmo que o valor seja negativo, sem fazer essa "Gambiarra" que eu fiz logo abaixo.
Existe alguma função que arredonde vidaInimigo, sem que seja necessário criar uma condição adicional: Se(vidaInimigo <= 0) entao EscrevaL("Vida: 0")?

Por que o inimigo tinha 4 de Vida, recebeu 39 de Dano, e ficou com -35 de vida.
Queria que fosse exibido a Vida igual a 0, e não -35.
Imagino que exista alguma função que arredonde pra cima.
Segue o código do algoritmo:
algoritmo "RPG"
var
   danoCausado, vidaInimigo, baseDanoPlayer: Inteiro
inicio
   baseDanoPlayer <- 50
   vidaInimigo <- 100
   EscrevaL("Vida: ", vidaInimigo)
   Repita
       danoCausado <- randi(baseDanoPlayer)
       vidaInimigo <- vidaInimigo - danoCausado
       EscrevaL(" >>> Dano causado: ", danoCausado)
       Se(vidaInimigo <= 0) entao
           EscrevaL("Vida: 0")
           senao
           EscrevaL("Vida: ", vidaInimigo)
       FimSe
   Ate(vidaInimigo <= 0)
   Se (vidaInimigo <= 0) entao
       EscrevaL("Inimigo abatido!")
   FimSe
fimalgoritmo

Comment: Não é dessa pergunta, mas nao deu tempo de eu comentar na que vc deletou: https://en.wikipedia.org/wiki/Printf_format_string - nao é especifico de Java, mas pode ajudar
Comment: Esse é mais especifico http://www.javawithus.com/tutorial/displaying-text-using-printf-method
Comment: E o link foi atualizado para double sem casa decimal, aplicando os links acima: https://ideone.com/irUPu3
Answer: Que tal substituir isso:
Se(vidaInimigo <= 0) entao
    EscrevaL("Vida: 0")
    senao
    EscrevaL("Vida: ", vidaInimigo)
FimSe

Por isso:
Se(vidaInimigo < 0) entao
    vidaInimigo <- 0
FimSe
EscrevaL("Vida: ", vidaInimigo)

Comment: Funcionou perfeitamente! Obrigado.


linq query on list id's

Question: I have a list of id's and I need to get all records correscponding to each id in the list .
below is the sample code
public List<Items> LoadLineItemByPkeys(IEnumerable<long> ItemId)
{
    var ItemList = CurrentSession.Query<LineItem>()
      .Where(l =>itemId.Contains(l.id))
      .ToList();
    return ItemList ;
}

but i am getting exception

An exception of type 'NHibernate.Exceptions.GenericADOException' occurred in NHibernate.dll but was not handled in user code

inner exception:-

Failed to convert parameter value from a WhereSelectArrayIterator`2 to a Int64.
  Please help me on this.

when i executed same query in LINQPad, i am getting the results.
Comment: So what does the full stack trace and message of the exception look like?
Answer: You may be having trouble due to how you've passed in the IDs. You may find that converting that sequence into a list or an array would help:
// Various names to be more conventional/readable
public List<Items> LoadLineItemsById(IEnumerable<long> ids)
{
    var idList = ids.ToList();
    return CurrentSession.Query<LineItem>()
                         .Where(item => idList.Contains(item.Id))
                         .ToList();
}

Answer: If i'm not mistaking you cannot make use of the contains method.
You'll have to make use of .IsIn()
public List<Items> LoadLineItemByPkeys(IEnumerable<long> itemIds)
{
    var lineItemList = CurrentSession.QueryOver<LineItem>()
      .WhereRestrictionOn(l =>l.id).IsIn(itemIds).List()
      .ToList();
    return lineItemList ;
}

This wil generate a sql statement with an in operator. Be aware of the limitations of this operator. Some db's have a limit of 1000 arguments, other of 2000 etc.

linq query on list id's


oracle value 99999999 getting rounded

Question: I created the below table:
create table ex_employee (id number(20,4));

Then I have insert the below values:
insert into ex_employee values (9999999999999999.9999);
commit;

The result is being rounded up;
10000000000000000.0000

In this link they explained if the precision execeeded then it will round up.
what should I do to keep the value not get rounded:
9999999999999999.9999
Comment: I think, it's just a display problem. See http://sqlfiddle.com/#!4/bb5f8/4
Comment: @Amadan I tried it and still causing problem
Comment: I'm a little confused: 1. Testing against Oracle 11g your code works as aspected ( nothing is rounded). 2. Enlarging the inserted number results as aspected in `ORA-01438: value larger than specified precision allowed for this column`.
Comment: @evilive mind is 11g also , I dont know why its giving me such result , if you need any information or query ill provide to you.
Comment: @DirkNM so I didnt understand ? is it normal ? If i insert it in my application it will give 99999999999.9999 result ?
Comment: DISPLAY from database and STORING into database are different. You got a display issue.
Answer:
The result is being rounded up [to] 10000000000000000.0000
what should I do to keep the value not get rounded: 9999999999999999.9999

As you noticed yourself, this is a display problem, as your NUMBER(20,4) has sufficient significant digits to precisely represent that base10 number.
If addition to Lalit's answer concerning "display format", a common source for that behavior is to use an IEEE 754 float/double values at application-level to read back those numbers (resp. 7 / 15 significant decimal digits only). In addition, all decimal digits cannot be accurately represented using binary representation.
If your host language has support for that, you should "long decimal numbers". For example, Java has BigDecimal. Python has Decimal.
Answer: Just set the numformat properly. In SQL*Plus, you could do it as set numformat.
SQL> set numformat 9999999999999999.9999
SQL> create table ex_employee (id number(20,4));

Table created.

SQL> insert into ex_employee values (9999999999999999.9999);

1 row created.

SQL> select id from ex_employee;

                    ID
----------------------
 9999999999999999.9999

SQL>

oracle value 99999999 getting rounded


Logistic regression: Overall significance of categorical predictor in SPSS

Question: In SPSS, when performing binary logistic regression using multiple categorical predictors, a significance level is detailed for the variable overall in addition to each category. This strikes me as useful as the model is built up as the addition of a predictor may negate the effect of previously added variables. What is this overall significance a measure of?
In R, the summary of my GLMs do not include this information. As I am building models I can anova(model0, model1) to test the impact of a new addition. However, how would one then detect if a previous predictor had become insignificant overall? Is the significance of a single category sufficient to warrant inclusion?
I have read the following article which was helpful:
Significance of categorical predictor in logistic regression
Comment: What do you mean exactly by previous predictors? Are they the predictors in model0?
Answer: To test if your previous predictor has become non-significant you make a new model without it and do the anova(model0,model1).  You might end up doing a lot of anovas, hence the issue with Type 1 errors that alesc mentions.
A better method might be to try model averaging - build all possible models, and then build a weighted average using the AIC scores.  This is relatively quick/straightforward to do using the package MuMIn.  One of the benefits is that it avoids decisions about what predictors to include, which can end up being somewhat arbitrary.
It also allows a rough significance test for each predictor based on the estimate, and whether the confidence intervals cross zero or not.
Answer: So basically, you are chaining statistical tests. Then you need to consider the Multiple comparisons problem in order to avoid Type I errors.
There are multiple methods to take this into account, but IMO the most convenient way is to use the Holm-Bonferroni method.


Call an assembler function from C code in linux

Question: I want to call a print function from my C program.
assembler prog:
<code> #test.s
.text

    .global _start
    .global print
    .type print, @function

_start:

        call print

        # and exit.

        movl    $0,%ebx         # first argument: exit code.
        movl    $1,%eax         # system call number (sys_exit).
        int     $0x80           # call kernel.

print:
    # write our string to stdout.

        movl    $len,%edx       # third argument: message length.
        movl    $msg,%ecx       # second argument: pointer to message to write.
        movl    $1,%ebx         # first argument: file handle (stdout).
        movl    $4,%eax         # system call number (sys_write).
        int     $0x80           # call kernel.

        mov $0,   %eax
        ret
.data

msg:
        .ascii  "Hello, world!\n"      # the string to print.
        len = . - msg                  # length of the string.
</code>
I can assemble and link it using:
<code>$as test.s -o test.o
$ld test.o -o test
</code>
And I can execute it as a program, and it outputs "Hello, world!"
But when I tried to call a print from C code like this:
<code>#include <stdio.h>
extern int print();

int main(){
    int g;
    g = print();
    printf("Hello from c!, %d\n", g);

}
</code>
It was compiled using:
<code>$gcc -c main.c test
</code>
It just prints "Hello from c, 13", that means that the function was called and return a number of chars, but does not print anything!
What am I doing wrong?
P.S.
When I trying to compile prog like this:
<code>$as test.s -o test.o
$gcc -c main.c -o main.o
$gcc main.c test.o
</code>
I have a error:
<code>/usr/bin/ld: test.o: in function `_start':
(.text+0x0): multiple definition of `_start'; /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/../../../../lib/Scrt1.o:(.text+0x0): first defined here
/usr/bin/ld: test.o: relocation R_X86_64_32 against `.data' can not be used when making a PIE object; recompile with -fPIE
/usr/bin/ld: final link failed: nonrepresentable section on output
collect2: error: ld returned 1 exit status
</code>
Comment: Does this help you resolve the -fPIE question? https://stackoverflow.com/questions/46123505/assembling-with-gcc-causes-weird-relocation-error-with-regards-to-data
Comment: That's 32-bit code.  Build it with `gcc -m32 main.c test.s -o main`.  You can optionally use `-fno-pie -no-pie` because that's a good idea for 32-bit for efficiency.
Comment: Great job in general, but I doubt sys_write() or write() actually uses printf() style formatting or looks at the additional arguments. Usually at the assembly language level one has to construct the formatted output in sections with multiple writes or build the formatted text into the data area and then write out the complete formatted buffer all at once. https://www.tutorialspoint.com/assembly_programming/assembly_system_calls.htm
Comment: Compiling with `gcc -no-pie -c test.s -o test.o` and `gcc -no-pie -o main main.c test.o` seems to do the trick ...
Answer: Ok, done! Thanks clearlight
I can compile all use
<code>$as test.s -o test.o
$gcc -c main.c -o main.o
$gcc -no-pie main.c test.o
</code>
And all will work fine!


Consider a recursive sequence. Find all values of x for which this sequence is bounded

Question: Consider a recursive sequence $a_{n+1} = a_n + a_{n-1}$ for all $n \geq 2$ with $a_{1} = 1$ and $a_2 = x$. Find all values of $x$ for which this sequence is bounded.
Comment: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. Please consider rewriting your post.
Comment: This is a duplicate question. Newcomers, especially young ones,should  also  be encouraged to  search the suggested list that is offered to them when they are posing and writing the Q.
Comment: Can you provide the link to the duplicate question, because I can't find it. Thanks.
Answer: Note that (similarly to the Fibonacci sequence) all such sequences must satisfy
$$a_n=\alpha \cdot a^n+\beta \cdot b^n$$ where $a,b$ are the roots of $x^2-x-1=0$ i.e. $a=\frac{1 +\sqrt{5}}{2},b=\frac{1 -\sqrt{5}}{2}$.
Since $|b|<1$ but $|a|>1$ it is necessary (and sufficient) for the sequence to be bounded to satisfy $\alpha=0$.
So $a_n=\beta b^n$ i.e. $\beta=\frac{1}{b}$ (by the condition $a_1=1$) and so $x=a_2=b=\frac{1-\sqrt{5}}{2}$ is the unique solution.


why are elements of unordered_set not unique for custom equal_to

Question: I am trying to understand unordered_set better. Mainly, to my understanding elements in an unordered_set should be unique up to equal_to operator.
Therefore, I decided to test that by a small piece of code
<code>#include <iostream>
#include <unordered_set>
using namespace std;

struct m_int
{
    int x;
};
// template specialization for std::hash
template<>
struct std::hash<m_int>
{
std::size_t operator()(m_int const& x) const noexcept
{

return hash<int>{}(x.x);
}
};
//template specialization for std::equal_to

template<>
struct std::equal_to<m_int>
{
bool operator()(const m_int &lhs, const m_int &rhs) const
{

return abs(lhs.x-rhs.x)<=3;
}
};
int main() {
    unordered_set<m_int> m={{1},{2},{3},{4}};
    for(auto&x:m)
        cout<<x.x<<' ';
    cout<<endl;
    cout<<m.count({2})<<endl;
    // your code goes here
    return 0;
}
</code>
My initial thought is that 1 would be inserted 2, and 3 would but 4 would be inserted.
The output I got was
<code>4 3 2 1
1
</code>
since according to my equal_to 1 and 2 are the same, then this set actually contains repetition, which is against the definition of the set. Why is that the case and how can I solve that?
Answer: Unordered containers have the following requirements for their hash and key equality functions:

If two Keys are equal according to Pred, Hash must return the same
value for both keys.

This is not true for your container. 1 and 4, for example, compare equal but they'll (almost certainly) have different hash values. This results in undefined behavior.
Another logical problem here: 1 is equal 4, and 4 is equal to 7, but 1 is not equal to 7. This does not compute, either.
Comment: See https://en.cppreference.com/w/cpp/named_req/EqualityComparable
Comment: Hello, I am the OP, is there a reason why you are assuming that equal_to is transative? I did not assume that and I don't think it says in the documents that it is . I mean A=B and B =C does not necessairly mean A = C and I am fine with that.


Get current country pathPrefix

Question: How can I get current country pathPrefix in D8 ?
I know drupalSettings.path.pathPrefix gives that in JS, but how can I get it in preprocess hook ?
Following gives only the path alias, but without pathPrefix.
\Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid[0]);

Answer: You can call PathProcessorManager::processOutbound() for the internal path and you get the path alias and the prefix at the same time:
$options = ['prefix' => ''];
$path = \Drupal::service('path_processor_manager')->processOutbound('/node/1', $options);
$prefix = $options['prefix'];

Get current country pathPrefix


how to implement a js function in an Angular 2 component

Question: I have a web page and I want to improve it with angular 2, and I would like to use my JS functions in the angular component, this is an example of what I have:
this is my app.component.ts:
import { Component } from '@angular/core';

@Component({
selector: 'myApp',
template: `

         Start:
         <select id="Hour" class="form-control">
         </select>

    `
})
export class MyApp {}

then I have my JS with a function that will fill the select with an inner-html:
function fillValues() {
var d = new Date();
var n = d.getHours();
var options = "";
for (var i = 0; i <= 23; i++) {
    if (i == n) {
        options += "<option id=" + i + " value=" + i + " selected>" + i + "</option>";
    } else {
        options += "<option id=" + i + " value=" + i + ">" + i + "</option>";
    }
}
document.getElementById('Hour').innerHTML = options;
}

and in the index.html I call the component and the JS:

    <myApp>Loading...</myApp>

my question is, how can I still use my JS functions and use them inside my components?
Comment: Nothing is stopping you from calling your old functions just like you have before.
Comment: I suggest rethinking that code in terms of Angular such that you're binding the options of the select to an array of numbers rather than setting the `innerHTML` of select manually.
Answer: Since all JS is valid Typescript, you can access your JS function without any problems. As you've included the script file in your index.html you need to tell Typescript that the function exists so you can call it, you can do that by placing;
declare var fillValues: any;

after your import statements. Then you can call the function as normal from you component. You likely want to do that in ngAfterViewInit() in this case, see the Lifecyle Hooks Docs for more details.
If you want to access the <select> element directly in typescript, there are a number of ways you can do that, @ViewChild for example. See this question for more details on how to do that.


Loop through all files in all folders recursively as fast as possible in GOLANG

Question: I'm facing a problem that even after spending the day on the forums I still can't quite understand and solve.
So here it is, I made a function that loops over all the folders as well as its sub-folders, and which has 2 sub-functions:
- For each file found, list the name of the file.
- For each folder found, restart the same parent function to find the child files and folders again.
To make it simpler, the macro lists all files in a tree with recursion. But my goal is to do it as fast as possible so I run a new goroutine every time I come across a new folder.
PROBLEM:
My problem is that when the tree structure is too large (too many folders in folders and subfolders...) the script generates too many threads and therefore gives me an error. So I increased this limit, but suddenly it's the pc that no longer wants :/
So my question is, how can I make a worker system (with poolsize) that fits my code?
No matter how much I look, I don't see how to say, for example, to generate new goroutines up to a certain limit, the time to empty the buffer.

Source code:
https://github.com/LaM0uette/FilesDIR/tree/V0.5
main:
package main

import (
    "FilesDIR/globals"
    "FilesDIR/task"
    "fmt"
    "log"
    "runtime/debug"
    "sync"
    "time"
)

func main() {
    timeStart := time.Now()
    debug.SetMaxThreads(5 * 1000)

    var wg sync.WaitGroup

    // task.DrawStart()

    /*
        err := task.LoopDir(globals.SrcPath)
        if err != nil {
            log.Print(err.Error())
        }
    */

    err := task.LoopDirsFiles(globals.SrcPath, &wg) // globals.SrcPath = My path with ~2000000 files ( this is a serveur of my entreprise)
    if err != nil {
        log.Print(err.Error())
    }

    wg.Wait()

    fmt.Println("FINI: Nb Fichiers: ", task.Id)

    timeEnd := time.Since(timeStart)
    fmt.Println(timeEnd)
}

task:
package task

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"
    "strings"
    "sync"
    "time"
)

var Id = 0

// LoopDir TODO: Code à supprimer / Code to delete
func LoopDir(path string) error {
    var wg sync.WaitGroup

    countDir := 0

    err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }

        if info.IsDir() {
            wg.Add(1)
            countDir++

            go func() {
                err := loopFiles(path, &wg)
                if err != nil {
                    log.Println(err.Error())
                }
            }()
        }

        return nil
    })
    if err != nil {
        return err
    }

    wg.Wait()
    fmt.Println("Finished", countDir, Id)
    return nil
}

// loopFiles TODO: Code à supprimer / Code to delete
func loopFiles(path string, wg *sync.WaitGroup) error {

    files, err := ioutil.ReadDir(path)
    if err != nil {
        wg.Done()
        return err
    }

    for _, file := range files {
        if !file.IsDir() {
            go fmt.Println(file.Name())
            Id++
        }
    }

    wg.Done()
    return nil
}

func LoopDirsFiles(path string, wg *sync.WaitGroup) error {
    wg.Add(1)
    defer wg.Done()

    files, err := ioutil.ReadDir(path)
    if err != nil {
        return err
    }

    for _, file := range files {
        if !file.IsDir() && !strings.Contains(file.Name(), "~") {
            fmt.Println(file.Name(), Id)
            Id++
        } else if file.IsDir() {
            go func() {
                err = LoopDirsFiles(filepath.Join(path, file.Name()), wg)
                if err != nil {
                    log.Print(err)
                }
            }()
            time.Sleep(20 * time.Millisecond)
        }
    }
    return nil
}

Comment: You can improve performance by using filepath.WalkDir instead of filepath.Walk.
Comment: https://github.com/panjf2000/ants this might be of use - it can manage your pool of goroutines so you can limit the number and rate limit.
Comment: profile, analyze, optimize. You have optimized an unprofiled, unalanyzed program. How do you know its bottle neck ?
Answer: If you don't want to use any external package, you can create a separate worker routine for file processing, then start as many workers you want. After that, go into the tree recursively in your main thread, and send out the jobs to the workers. If any worker "has time", it will pick up the following job from the jobs channel and process it.
var (
    wg   *sync.WaitGroup
    jobs chan string = make(chan string)
)

func loopFilesWorker() error {
    for path := range jobs {
        files, err := ioutil.ReadDir(path)
        if err != nil {
            wg.Done()
            return err
        }

        for _, file := range files {
            if !file.IsDir() {
                fmt.Println(file.Name())
            }
        }
        wg.Done()
    }
    return nil
}

func LoopDirsFiles(path string) error {
    files, err := ioutil.ReadDir(path)
    if err != nil {
        return err
    }
    //Add this path as a job to the workers
    //You must call it in a go routine, since if every worker is busy, then you have to wait for the channel to be free.
    go func() {
        wg.Add(1)
        jobs <- path
    }()
    for _, file := range files {
        if file.IsDir() {
            //Recursively go further in the tree
            LoopDirsFiles(filepath.Join(path, file.Name()))
        }
    }
    return nil
}

func main() {
    //Start as many workers you want, now 10 workers
    for w := 1; w <= 10; w++ {
        go loopFilesWorker()
    }
    //Start the recursion
    LoopDirsFiles(globals.SrcPath)
    wg.Wait()
}

Comment: great I just tested and it works flawlessly  thank you again
Comment: great thank you for your answer, I will test it once I get home but already I understand much better how to use workers, thank you
Comment: Two quesions:
1. Whould the waitgroup be declared as pointer? Didn't work for me.
2. Are threads speeding things up here? My experiment shows that one worker goes a little faster than 10...


Speech recognition without predefined Choices in C#

Question: I'm trying to develop a SpeechRecognition demo app in C#. Currently my code is-
public partial class Form1 : Form
{
    SpeechSynthesizer ss = new SpeechSynthesizer();
    PromptBuilder pb = new PromptBuilder();
    SpeechRecognitionEngine sre = new SpeechRecognitionEngine();
    Choices choices;
    public Form1()
    {
        InitializeComponent();
    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        choices = new Choices();
        choices.Add(new string[]{"hello","how are you","thank you"});
        Grammar gr = new Grammar(new GrammarBuilder(choices));
        try
        {
            sre.RequestRecognizerUpdate();
            sre.LoadGrammar(gr);
            sre.SpeechRecognized += sre_SpeechRecognized;
            sre.SetInputToDefaultAudioDevice();
            sre.RecognizeAsync(RecognizeMode.Multiple);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message,"Error");
        }
    }

    void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
        switch (e.Result.Text.ToString())
        {
            case "hello":
                ss.SpeakAsync("hello");
                break;
            case "how are you":
                ss.SpeakAsync("how are you");
                break;
            case "thank you":
                ss.SpeakAsync("thank you");
                break;
            default:
                break;
        }

        txtVoiceToText.Text += e.Result.Text.ToString() + Environment.NewLine;
    }
}

If I don't want to use any predefined Choices, is there any way out?
Answer: Try SpeechRecognition in DictationMode. You can see example here


How to use NLP in Python to extract the 'subject' of a question using NLTK trees

Question: I am trying to figure out how to understand a question in Python. The aim is to use this for an information retrieval chatbot - i.e. the user will ask for information about something, and then the chatbot will access a knowledge base to return information about that something.
Example user inputs may be:
"Show me information about WW1." - where [WW1] should be extracted
"I want to know the symptoms of the common flu." - where [the symptoms of the common flu] should be extracted
I have started of by looking at spacy and nltk, specifically nltk trees, which end up looking like these:
<code>    Show
  ___|________
 |   |   information
 |   |        |
 |   |      about
 |   |        |
 me  .       WW1

        want
  _______|________
 |   |           know
 |   |    ________|______
 |   |   |            symptoms
 |   |   |     __________|______
 |   |   |    |                 of
 |   |   |    |                 |
 |   |   |    |                flu
 |   |   |    |           ______|____
 I   .   to  the        the        common
</code>
From here, I'm not sure how to extract the correct subtree as shown above, and I don't want to have to assume it will always be the right hand most tree.
I also don't know if this is the best way of tackling this problem?
Once I have the string value of which the user wants information about I can use this to find the information, I just need to get this value first.
Answer: SpaCy is a good library for this type of problem. This code is similar but more informative than nltk trees, as it includes directed dependency types and part-of-speech tags.
<code>import spacy
from spacy import displacy

nlp = spacy.load('en_core_web_lg')

doc = nlp('I want to know the symptoms of the common flu.')

# retokenize noun chunk spans
spans = spacy.util.filter_spans(doc.noun_chunks)
with doc.retokenize() as retokenizer:
    [retokenizer.merge(span, attrs={"tag": span.root.tag, "dep": span.root.dep})for span in spans]

options = {"compact": True, "font": "Source Sans Pro"}
displacy.serve(doc, style="dep", options=options) # see on http://localhost:5000/
</code>
Answer: Try stanford's dependancy parser. It analyzes the grammatical structure of a sentence and provides information like pos tags dependency relations , from which you can easily identify subject and objects in a given sentence. Check the website https://nlp.stanford.edu/software/nndep.html.