What's most flexible for my use cases, Acoustic amp vs portable PA?

Question: I'm torn between buying an acoustic amp or a portable PA system. My challenge is that I'd like the flexibility for certain uses:

Would like to do karaoke nights with kids and/or adults in the basement. I already have mics but we don't have a good stereo system (yet!) Acoustic amp is limited to 2 inputs so we can duet and that's probably sufficient.
Playing music with friends in the house for "mini-gigs" where we'd need 1-2 mics and possibly acoustic-electric/keyboard amplification. Depending on the room we'd might only use the amp for vocals. This seems like a PA system would win if I wanted to accommodate 1-3 instruments + 1-2 mics or my friends need to bring some equipment over.
Solo performances where I self-accompany on a digital keyboard. I was thinking acoustic amp here wins because it's a lot less components/complexity and sufficient sound for small venues (either in my house or coffee shops).

The struggle I have here is that it seems like the PA system is the best bet for maximum flexibility and allows me to supply most of the equipment for a small band in the future (my 1 year goal right now). However, the acoustic amp is less expensive, less complicated, less weight, but less flexible (for my future goals!)
I'm looking at these products currently Fishman acoustic amp with combo inputs for 1 instr/1 mic or 2 mics or Fender acoustic amp VS Yamaha STAGEPAS 600BT Portable PA System with Bluetooth. All 3 of these would also allow me to connect bluetooth/aux for backing tracks for performances or karaoke.
Thanks for your help!
Comment: If you want a PA system, I recommend the RCF Art 3xx series powered speakers, and a separate mixer, https://www.amazon.com/RCF-ART310MK3/dp/B006ECDAE6/  The RCFs can cover a very large crowd. What comes to the acoustic amps, they're for one singer and a guitar. IMO, you should think of the acoustic amps as _my sound_, or what _I_ sound like. Like, this amp is an extension of my instrument and myself as a player.
Answer: Hi and welcome to the site! Thanks for asking this question!
For your case, it seems like you've already identified the PA system will be the most flexible to your immediate and future needs.
Even in your last use case, using the amp as accompaniment while playing piano, will be more easily accomplished using a PA system. This is for three reasons:

Your acoustic amp may not have two separate inputs to supplement a backing track + piano input, and
even if it does have two inputs, it most likely won't have mixing (volume leveling) capability for the two inputs independently. Most PA systems will have mixer channels with EQ and Volume knobs on each mixer input, allowing you to more easily mix your outputs' volumes, by adjusting the PA instead of the volume levels on the instruments/computers in use.
Finally, aside from the most intimate settings (single room, 20-30 people) a single amp will likely not give you enough power to broadcast at a high volume and clarity to an audience, especially in a "noisy" (bar-like) setting with conversations. In fact, some amps will sound worse (subjectively) as you increase the volume, because the gain running through the amplification circuits can cause some distortion of the signal. This may be a desired effect in some settings; in fact, this is why some vintage amps are so expensive, they have a natural character to their distortion that is difficult or impossible to reproduce; but you probably won't want that if you're just putting voice + piano through the amp.

The only advantages I can think of to having an acoustic amp for your use case would be the price factor and the lug factor. Depending on your choice of brand and vintage, you can likely find an amp for far cheaper than a PA system, and the amp (if a combo amp) will have speakers built in, reducing the amount of gear to lug around and keep track of.
I hope this advice helps you! Best of luck in making your purchase!
Comment: Just wanted to comment and follow up: After looking at your links, it looks like the acoustic amp you're looking at has two inputs and EQ/leveling for each input. So that invalidates points 1 and 2 above for that Fishman amp specifically. They're still good things to keep in mind regarding amps in general, so I'm leaving it. :)
Answer: Often acoustic amplifiers are designed to compliment an acoustic instrument specifically using electronic design and speaker design that colors the sound in a certain  fashion. Hopefully that is not the case with a well designed P.A., where it is more important to reproduce accurately the original sound, only louder, in order to cover a larger audience. A well designed P.A. offers considerably more flexibility both in actual operation and use, and also in the possibility of expanding the system in the future. My own perspective would cause me to go ahead and invest the additional expense in the P.A. if I seriously planned to pursue such an idea, but of course the final choice is yours to make.


save draggableview weight

Question: I have a question related to draggableview (DV) integrated in Drupal 9. How can I save DV weight field value in other content type field called "field_priority" ?
I found this info but it's using form submit event to get the field value. not clear about how I can integrate this code into my custom module. save weight field value
DV custom view

Content Types custom field
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: hi, finally I solved the issue. thanks.
Answer: This is what I did to solve the requirement. Installed a module called Sortableview This one is similar to Draggableview module except it can save the position value ( After drag and drop the question ) into custom content type field.
Here are the steps:

composer installed the Sortableview module
create a new integer field called field_priority (content type)
added that field as a sorting criteria to the custom Drupal view
added Sortableviews: Drag and drop handler as a field to the custom view
change the format to the Sortable table
finally added the Save Sortableviews changes handler to the footer of the custom view

save draggableview weight


select future dates only django form

Question: I'm using the SelectDateWidget in my form.
Now I want to ensure that the form should only allow future dates, the widget should not set the past dates.
Is there any way that the widget itself should handle it, it should start from tomorrow's date.
forms.py
import datetime
from django.forms.extras.widgets import SelectDateWidget
class HmsDiagnosisForm(ModelForm):
    reconsultation_date = forms.DateField(widget=SelectDateWidget)

Answer: The SelectDateWidget does not support this functionality.
You could try to extend the functionality of the SelectDateWidget yourself, but I would suggest using a different widget, for example the jQuery UI datepicker. It does allow you to restrict the date range.
It's pretty straight forward to set up the datepicker widget with Django, and several  questions about it on stack overflow already if you get stuck.
Remember, that restricting the dates on the client side is useful, but it's important to validate the data in your model form on the server side as well.
Comment: thank you..
it was a good suggestion..
i got it working the JQuery Date widget

select future dates only django form


Physical disk or VHD for Hyper-V R2

Question: Using Hyper-V, what are the pros/cons of using the "Physical Hard Disk" option when adding a drive to a VM  as opposed to just creating a fixed-size VHD that is as large as the disk?
The intention is for this disk to be allocated to a single VM so there isn't any requirement to have anything else using it.
Comment: There's also a new whitepaper from MS - http://download.microsoft.com/download/0/7/7/0778C0BB-5281-4390-92CD-EC138A18F2F9/WS08_R2_VHD_Performance_WhitePaper.docx - Virtual Hard Disk Performance
Comment: Thanks for everyone's comments - I feel more informed now. In this particular case the VM is running Windows Home Server, so portability isn't such a high requirement, but I appreciate it is something to consider generally.

-dave
Answer: I use VMs because they are portable.  When you attach a physical disk, you lose most of the portability. It is much easier to copy a VHD file to another host than it is to move the physical disk between them.
Answer: The thing you have to think about is portability versus speed. It is largely accepted that giving a VM a real raw disk to work with is the largest performance gain you can make. When a VM runs in a file, it has an operating system thinking it's writing to a file, which in turn is asking an external operating system to write to a disk.
Disk write performance is probably the largest problem a VM can have.
More information:  Coding Horror: The Single Most Important VM Performance Tip
Comment: While it's true that VM performance can be greatly increased by making sure that the VM has adequate storage bandwidth, even the guy you're siting doesn't try to say that you have to expose the disk directly to the VM.  He just says that you should dedicate a disk to your VM.  Putting a VHD file on that disk preserves flexibility without compromising performance much.
Comment: Depends. Really. I have a disc exposed that already spans 6 physical discs and soon will go to about 12 - in a RAID 10. Sometimes perforamnce trumps everything.
Comment: VM performance is often impacted by the *sharing* of a physical disk or disk array between multiple systems. However, the overhead imposed by the use of a VHD file is not nearly as dramatic as you have suggested.
Comment: I wonder if this is still true for SSDs. This article is from 6 years ago.
Comment: regardless of hard disk speed having to go through a layer of virtualisation before actually writing to the disk was the speed issue
Answer: I doubt that you could measure any performance difference incurred by putting a VHD on that single disk.  Try it and see.  I suspect you'll want to preserve the flexibility that BLAKE mentioned.
Answer: Something else to consider: as soon as you attach a pass-through disk, you lose the ability to take snapshots of that VM. The only workaround is to detach the disk, take the snapshot, and reattach the snapshot. It must be a SCSI disk in order for this to work. You also will want to make sure the VM is not writing to the disk before detaching it.

Physical disk or VHD for Hyper-V R2


The "set of all possible worlds", etc.

Question: The following is an excerpt from a highly-respected paper (Angelica Kratzer, Modals and Conditionals: New and Revised Perspectives, chapter 1 "What Must and Can Must and Can Mean")  (my emphasis):

In the possible worlds semantics assumed here, propositions are identified with sets of possible worlds.  If $W$ is the set of possible worlds, the set of propositions is $P(W)$—the power set of $W$.

Is it valid to speak of the set of something as ill-defined as "possible worlds" (let alone its power set)?
I mean, we can go on with "the set of all titillating nightmares", and "the set of all deceptively simple buffalo-wing recipes", and on, and on, and on, and thereby cloak the most outlandish ideas with an appearance of formal rigor...
Is there anything in standard set theory to prevent this sort of nonsense?
Comment: Post in haste, repent at leisure.
Comment: Samuel's answer shows that your misgivings are unwarranted, and simply the result of not being aware of standard terminology. Please consider editing the question so it doesn't read so much as a rant.
Comment: I think you asked a reasonable question, even if you didn't mean to, and Samuel Reid gave you an excellent answer.  Why would you want to delete it?
Comment: 20 revisions in one day. Voting to close.
Comment: You edited your question to include the "mumbo-jumbo-free" comment. The point of my answer is to explain the basic idea of modal logic and the fact that the notion of "possible worlds" and "set of all possible worlds" in Kripke semantics is not an ill-defined notion and is in fact perfectly rigorous. Do you want a more intuitive explanation of one or more aspects of my answer? I am willing to provide any answers to your questions regarding this topic, but you must be more specific as to exactly what you are looking for.
Comment: I just typed up my answer off of the top of my head because I have written modal logic research papers. What are you looking for? These are common notions which any mathematician or logician familiar with modal logic will understand, similar to how any math student who has taken calculus 1 can explain the derivative of a function to someone.
Comment: What is this "prior authority" you are referring to? I took the time out of my day to type up a response to your question and you are not exactly being easy to work with. Do you have any questions about what I wrote or have other questions which I could help answer? What I have explained IS the idea, I am not referring you to a reference or using words you can't understand.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9483/discussion-between-samuel-reid-and-kjo)
Comment: And please don't add back irrelevant tags. Something that mentions sets is not necessarily about set theory. The relevant tag here is modal-logic.
Comment: @kjo: I am willing to give you a satisfying answer if you just tell me what you want to know! As it stands your question is "Is it valid to speak of the set of something as ill-defined as "possible worlds"?". I have answered this question, please edit your question if you are interested in something else.
Comment: Please don't deface your posts.
Comment: @kjo: Please don't vandalize your question.
Answer: In modal logic we use the term "possible worlds" to describe some set of "vertices" with an accessibility relation defining "edges". Possible worlds are just a term for some set $W$ which we wish to identify as our frame in the context of Kripke semantics. When we define a valuation on that frame we obtain a model which has certain modal formulas being satisfied depending on the structure of the vertices and edges (in the graph theory sense).
Formally, $\mathcal{F} = \langle W,R \rangle$ is a frame, where $R \subseteq W \times W$, and $\mathcal{M} = \langle W,R, \text{Val}\rangle$ is a model where $\text{Val}: \text{Var} \times W \rightarrow \{0,1\}$ is a valuation function which sends propositions in the set $\text{Var}$ at a world $w \in W$ to a truth value (we can also define probabilities that a modal formula is satisfied at a world by considering a valuation function with values which map to the interval $[0,1]$). Depending on the structure of the accessbility relation $R$, we can have different modal axioms satisfied in the model.
For example, consider the modal axiom $B = p \rightarrow \Box \Diamond p$. If we have that $\mathcal{M}_{w} \vDash B$, $\forall w \in W$, which is read as "the model $\mathcal{M}$ makes true $B$ at all possible worlds", we say that $\mathcal{F} \vDash B$, which is that $B$ is satisfied in the frame $\mathcal{F}$. In this case, the satisfaction of $B = p \rightarrow \Box \Diamond p$ in all possible worlds ensures that the accessibility relation $R$ is symmetric, that is, $w R w' \Rightarrow w' R w, \forall w,w' \in W$. We can characterize modal frames by the satisfaction of modal axioms in this way and give an interpretation of the philosophical phrases such as "it is possible that $\varphi$" and "it is necessary that $\psi$."
In summary, $W$ is just the vertex set of a graph and modal logic studies the satisfactions of modal formulas and other properties of frames and models. I should probably mention that the following are the formal definitions of possibility and necessity.
$\mathcal{M}_{w} \vDash \Diamond \varphi \Leftrightarrow \exists (w,w') \in R \; | \; \mathcal{M}_{w'} \vDash \varphi$
$\mathcal{M}_{w} \vDash \Box \varphi \Leftrightarrow \forall (w,w') \in R \; | \; \mathcal{M}_{w'} \vDash \varphi$
We can define other modalities in a similar manner, thus generalizing to temporal logic, epistemic logic, and other interesting types of logic. Here is a pretty picture I made which gives an example of a model with an orientation (a directed graph upwards as this is representing temporal logic).
Answer: $\def\diamond{\diamondsuit}$
Modal logic is concerned with the logic of so-called "modal operators", often "necessarily true" and "possibly true", which are symbolized with $\square$ and $\diamond$ respectively.
The idea is that while it is true that George Bush was the 43rd president of the United States, it is not necessarily true, because one can easily imagine a slightly different world in which Al Gore was president instead—it was the closest of close elections. Considering the statements:
$$
B = \text{The 43rd president was Bush}\\
G = \text{The 43rd president was Gore}
$$
We can say unequivocally that $B$ is true and $G$ is false.  But we could also say that $B$ is not necessarily true; that is $\lnot\square B$, or equivalently that it is possible that $B$ could have  been false: $\diamond\lnot B$. And we could say that $G$ is possibly true; that is $\diamond G$, or equivalently that $G$ is not necessarily false; that is $\lnot\square\lnot G$.
On the other hand if we consider the statement:
$$ P = \text{$131$ is a prime number} $$
we can't reasonably think of a possible world in which $P$ is false, so we might say that $P$ is "necessarily" true; that is $\square P$, or equivalently that it is not possibly false: $\lnot\diamond\lnot P$.
Now any sophomore philosophy major could argue for hours about whether it was really possible for Gore to have been elected president in 2000 or whether it is necessarily true that 131 is a prime number.  So we sidestep such arguments about what "necessarily true" and "possible world" actually mean and consider a generalization.  In the generalization, we consider some set $W$ of world-states, some set of "possible worlds".  And we say that some of these worlds are "accessible" from others: for example, we might like to say that before the 2000 election, it was possible that Gore would have been the 43rd president, and after the election it was no longer possible.  Our set $W$ might include a state $E$ before the election, and a state $B$ where Bush had been elected, and a state $G$ where Gore had been elected, and then we might say that $G$ is accessible from $E$ but not from $B$; we find ourselves now in $B$.  Once we have chosen this "accessibility" relation, we take "$\diamond S$ is true in world $W$" to mean "There exists some world $W'$, accessible from $W$, in which $S$ is true".  And we take "$\square S$ is true in world $W$" to mean "For every world $W'$, accessible from $W$, it is the case that $S$ is true".
The idea is not to try to construct a "set of all possible worlds", which I agree with you might be philosophically and mathematically incoherent.  All we are doing is selecting some reasonable set of worlds to consider, for the purpose of understanding behaviors of modal operators such as $\square$ and $\diamond$.
It develops that this is an interesting thing to do!  Certain intuitively reasonable axioms for the modal operators correspond naturally to certain simple conditions on the "accessible" relation.  For example, consider the very reasonable axiom that $\square p\to p$.  This says that if $p$ is necessarily true in some world $W$, then it in fact true in $W$. This axiom holds exactly if the accessibility relation is reflexive; that is, if $W$ is accessible from itself for each possible world $W$ under consideration.
One similarly likes to consider modal operators such as "could become true in the future" and "was false in the past", where the accessibility relation is usually understood to represent the evolution of time; "is known to be true", "is provable", and "is consistent with ZF"; "is permitted", and so forth. Each of these has different properties, and is formalized by different axioms, and gives rise to a different sort of accessibility relations on the possible worlds.  The intuitions about the meanings of the modal operators help inform the intuitions about the accessibility relations, and vice versa.
But again, the "possible worlds" don't represent the entirety of the universe.  They are only abstractions that have certain simplified relations that allow us to capture interesting features of logical operators. In this way they are not at all different from other mathematical abstractions.
I hope this clears something up for you.
Comment: It may be interesting to note the de re versus de dicto reading of the "president of the united states in 2000" example which can be understood via lambda abstraction as dependent upon the scope of the modal operator: http://en.wikipedia.org/wiki/De_dicto_and_de_re

The "set of all possible worlds", etc.


How to use Schur's decomposition on more than two commuting matrices?

Question: If we have more than two square matrices $A$, $B$, $C$,... commute, how can we prove that there exits a unitary matrix $U$ such that  $U$ * $A$ $U$,  $U$ * $B$ $U$, $U$ * $C$ $U$,.... are upper triangular matrices?
Following from Schur's decomposition for two commuting matrices, it works.But for more than two,I tried to prove it by induction but could'nt reach it.
Answer: The point lies in the proof of Schur decomposition. Let $A^{(1)}, A^{(2)}, \cdots, A^{(k)}$ be $k$ square matrices which mutually commute with one another. Let the set of eigenvalues of $A^{(j)}$ be $\{\lambda^{(j)}_1, \cdots, \lambda^{(j)}_{n_j}\}$. Also let the eigenspace of $A^{(j)}$ corresponding to eigenvalue $\lambda^{(j)}_{s}$ be denote by $V^{(j)}_s$.
Now if $v\in V^{(1)}_j$ for some $j\leq n_1$, then since $A^{(1)}, A^{(2)}$ commute, we have $A^{(1)}A^{(2)}v=A^{(2)}A^{(1)}v=\lambda^{(1)}_jA^{(2)}v$. So $A^{(2)}v\in V^{(1)}_j$ too, meaning $A^{(2)}$ leaves $V_j^{(1)}$ invariant. As a result $V_{m_1}^{(1)}\cap V_{m_2}^{(2)}$ is not only invariant under both $A^{(1)}, A^{(2)}$, but both matrices act on $V_{m_1}^{(1)}\cap V_{m_2}^{(2)}$ diagonally. Similarly one can decompose $V$ into:
$$
V=\bigoplus_{m_1, \cdots, m_k} \left(\bigcap_{i=1}^k V^{(i)}_{m_i}\right)
$$
where $m_j\leq n_j$ in the above sum. You can see that all $A^{(i)}$ leave $U_{m_1, \cdots, m_k}:=\bigcap_{i=1}^k V^{(i)}_{m_i}$ invariant and act on it diagonally. Now choose an orthonormal basis $Z_{m_1, \cdots, m_k}$ for $U_{m_1, \cdots, m_k}$. This gives you a unitary matrix $T$ such that $A^{(i)}=T^*F^{(i)}T$ with $F^{(i)}$ upper-triangular.


Logistic regression coefficients

Question: I am doing logistic regression with 3 attributes. According to my data set I am expecting all coefficients to be positive. But it gives me both positive and negative coefficients. Is it possible to have all positive coefficients using logistic regression.
Comment: Are you expecting the coefficients on the log odds scale to be positive?
Comment: no, i want the logistic regression coefficients to be positive
Comment: Do you have any regression software that allows setting bounds on the parameters? If so, you could set all of the lower bounds at zero.
Comment: Can you post the output of your software?
Answer: Yes, it is possible to have all positive coefficients in logistic regression.
That doesn't say very much, if a covariable $x$ have a negative coefficient you can just replace that covariable by $-x$ and get a positive coefficient ... you would get a more useful answer if you told us about your real problem, your data, the context and research questions.

Logistic regression coefficients


Is it expected to get NPE on isAutoCommit or getUpdate on a fresh Session object in MarkLogic 9?

Question: Under MarkLogic XCC version 9.0-3, I get a NullPointerException when trying to call isAutoCommit or getUpdate on a fresh Session object.
The NPE does not occur if either setAutoCommit or setUpdate is called first. Is this intentional behavior? If so, why? All other getters for Session return without error even if no value is set.
I've constructed a minimal viable example:
import java.net.URI;

import com.marklogic.xcc.ContentSource;
import com.marklogic.xcc.ContentSourceFactory;
import com.marklogic.xcc.Session;

public class mve {
    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("usage: xcc://user:password@host:port/contentbase");
            return;
        }

        System.out.println("Running minimal viable example of MarkLogic isAutoCommit/getUpdate bug...");

        URI uri = new URI(args[0]);
        ContentSource contentSource = ContentSourceFactory.newContentSource(uri);
        Session updateSession = contentSource.newSession();

        // comment out the following two lines to cause a NullPointerException to be thrown on getUpdate and isAutoCommit:
        updateSession.setAutoCommit(false);
        updateSession.setUpdate(Session.Update.TRUE);

        System.out.println("is AutoCommit?");
        System.out.println(updateSession.isAutoCommit()); // if lines 21 and 22 are both commented out, this will cause NPE

        System.out.println("getUpdate?");
        System.out.println(updateSession.getUpdate());  // if lines 21 and 22 are both commented out, this will cause NPE
    }
}

Answer: Both of those methods attempt to access properties of the TransactionMode, which is null.
Invoking either setAutoCommit() or setUpdate(), or explicitly setting the TransactionMode with setTransactionMode() will ensure that the txnMode is not null.
If you upgrade to 9.0.4, the SessionImpl isAutoCommit() will return a default true without an NPE:
public boolean isAutoCommit() {
    return txnMode == null ? true : txnMode.isAutoCommit();
}

but you will still get an NPE if you invoke getUpdate() without a txnMode being established:
public Update getUpdate() {
    return txnMode.getUpdate();
}

It is probably reasonable to expect that it return a default TransactionMode.AUTO instead of an NPE.
Comment: I notice that the change to `isAutoCommit` behavior is unfortunately not documented in the [9.0-4 release notes](https://docs.marklogic.com/guide/relnotes/chap3#id_29897).


Duvidas sobre Models relacionais no Django

Question: Olá,
Estou criando um sistema de Blog com o Django, nele eu tenho vários Models: Profile(que recebe um auth.User), Post(que tem um field author que recebe um Profile).
Estou desenvolvendo uma pagina para realizar a atualização de um Post, eu sei que a função user.is_authenticated verifica se o usuário está conectado, em meu caso como faço para saber se o usuário que está conectado é o mesmo do Post
Segue o código que está no meu template:
<code>{% user.is_authenticated and user.id == post.user %}
   ......
{%endif%}
</code>
No caso ele me retornaria um object Profile e nao User, como faço para saber o User do profile, seria correto usar post.user.profile ?
Answer: Vai depender de como estão estruturadas as relações entre os seus models, para comparar se o usuário é o mesmo que realizou a publicação você precisa comparar o usuário do request com o vinculado com o do post.
Pela sua descrição me parece que o caminho seria post > author > user, pois pela descrição "o post tem um campo author que tem vinculo com o auth.User" então ficaria assim:
<code>{% user.is_authenticated and user == post.author.user %}
   ...
{%endif%}
</code>


CakePHP: Limiting number in a group

Question: I'm creating sort of a game, and I want people to be able build a town.
Each user can only build a limited number of a specific buildings in their town (i.e. only 2 post offices, 1 city hall etc.)
I'm struggling with how to implement this.
I have a UserBuildings table to keep track of the user/building associations, a Buildings table and a User table.
On the form where I add a building to my city, I want to first check the building's limit, and omit it from the list of available buildings if it's been reached. Here's what I have:
$buildings = $this->UserBuildings->Buildings->find('list');
$currents = $this->UserBuildings->find('all', array(
    'conditions'=> array(
        'UserBuildings.user_id'=>$this->Auth->user('id')
    )
));

I can get the limits from the $currents array.
Is there a way, via find and query in which I can add some conditions to my $buildings list to remove any entries with a capacity reached.
Obviously, I can run a compare via a for loop and build a more refined list by checking capacities against number of matching entries in the UserBuildings table, but is there a more elegant method, perhaps using CakePHP's own methods?
Comment: Not what I was trying to do... I'm trying to remove entries that break a pre-set limit value from my result set
Comment: Sorry for my previous comment, didn't read the first part properly. I don't have a direct answer for you at the moment. Have you considered using calculated values (possibly using a database view). You'd be able to calculate the number of buildings (per type) used by a user via a 'count()' and group by user_id, building_type. This will always give you an up-to-date value, also if the user *removed* a building. You can include calculated fields in your model by defining them as a virtualField; http://book.cakephp.org/2.0/en/models/virtual-fields.html
Answer: Simply count how many buildings of a type an user has. By adding a new building you should already know it's id and other data.
Assuming this is ja join table:
$count = $this->UserBuildings->find('count', array(
    'conditions'=> array(
        'UserBuildings.building_id'=>$buildingId,
        'UserBuildings.user_id'=>$this->Auth->user('id')
    )
));

You can then simply compare the count with your limit for that building. all of that should happen in a model by the way.
Comment: I built this into a loop and checked each building against it's limit to build an array. Thanks for your input.

CakePHP: Limiting number in a group


How to use aurelia without module loaders?

Question: I'd like to use aurelia in small mobile cordova apps. Is it possible to omit any module loaders like requirejs and use an aurelia bundle directly in a script tag like
<code>  <script src="scripts/aurelia.js"></script>
</code>
?
Thanks,
George
Comment: sorry i've let a lot of questions go unanswered as i've been busy lately. the answer here is to use jspm bundle. you can find more information doing a google search or checking out this article: http://patrickwalters.net/my-best-practices-for-aurelia-bundling-and-minification/ I plan to put together my own article soon.
Answer: You can use JSPM to build a self executing bundle complete with system.js, and then you only need to include that one script. (no other dependencies are required)
Check out the docs on production workflows for JSPM for more details:
https://github.com/jspm/jspm-cli/blob/master/docs/production-workflows.md#creating-a-self-executing-bundle
Comment: nice, i will try that and come back to you! Thanks.
Answer: You could bundle your modules using requirejs' and then use almondjs to load your modules.
I know you said 'omit any module loaderes' but I don't think thats possible unless you wrote your own code to wire your modules together.  They just wont work automagically.  Your going to need some kind of module loader.  Almondjs is a lightweight AMD module loader. It does not do any dynamic loading or fetching of modules. It's meant to only load modules which have already been bundled together.
So, what I have seen in the past is people would use requirejs during development but when they are releasing to production they would bundle their app using requirejs' bundler and then use almondjs in place of requirejs.
I was hoping someone else would answer this question because its been a long time since I've looked at almondjs. I'm wondering if there are any other solutions out there.


Como pegar o item selecionado

Question: Olá, gostaria de uma ajuda,
Estou usando o framework da DEVEXPRESS.
Tenho um formulário com uma GridControl,
nesse GridControl tenho um evento DoubleClick.
Quando eu der um click na linha selecionada quero pega apenas apenas o ID
da linha. Usando um grid normal eu faço esse código para conseguir:
private void gvDados_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                this.codigo = Convert.ToInt32(gvDados.Rows[e.RowIndex].Cells[0].Value);
                this.Close();
            }
        }

Nesse código eu consigo pegar o ID da linha que cliquei, mas quando uso o componente da DEVEXPRESSS GridControl, não tem o evendo CellDoubleClick, só o
evento DoubleClick. Já tentei varias coisas, mas sem exito de pegar o ID da linha selecionada.
Se alguém ajuda, agradeço
Comment: tem que ser com double click? Se não me engano, o o grid control do dev não aceita double click nas rows
Comment: não tem uma função chamada GetFocusedRow() ? Geralmente ela retorna o objeto que está na linha.
Answer: Boa noite, utilize o seguinte codigo para obter o valor da grelha na linha selecionada:
 gvDados.gettext(colunaID,grelha.activerow)

A coluna do id é sempre a mesma, a linha é a linha activa no momento.
Na sua linha têm de colocar a coluna correta que não pode ser 0. Mas sim a definida para id. Se for a 1a da grelha é 1:
this.codigo = Convert.ToInt32(gvDados.Rows[e.RowIndex].Cells[1].Value);

Comment: Boa noite Daniel, eu estou usando o seguinte evento
 `private void gvDados_DoubleClick(object sender, EventArgs e)
        {

        }`
Devido o GridControl da DevExpress não ter o evento CellDoubleClick, logo eu não consigo usar o seguinte código que mencionei em cima.
Comment: Veja se o seguinte código ajuda:

private void gvDados_DoubleClick(Object eventSender, EventArgs eventArgs)
{
      int Index = Array.IndexOf(this.gvDados,eventSender);

      if (Index  >= 0)
      {
               gvDados.GetText(ColunaID, Grelha.ActiveRow);

      }
}

Testei com a grelha da devExpress no VS
Answer: Olá,
Utilizando o evento "DoubleClick" do DevExpress seria quase a mesma coisa.
private void grdView1_DoubleClick(object sender, EventArgs e)
    {
        int index = grdView1.GetFocusedDataSourceRowIndex();
    }

Como pegar o item selecionado


How to make sympy simplify a radical expression equaling zero

Question: The three (real) roots of the polynomial x^3 - 3x + 1 sum up to 0. But sympy does not seem to be able to simplify this sum of roots:
>>> from sympy import *
>>> from sympy.abc import x
>>> rr = real_roots(x**3 -3*x + 1)
>>> sum(rr)
CRootOf(x**3 - 3*x + 1, 0) + CRootOf(x**3 - 3*x + 1, 1) + CRootOf(x**3 - 3*x + 1, 2)

The functions simplify and radsimp cannot simplify this expression. The minimal polynomial, however, is computed correctly:
>>> minimal_polymial(sum(rr))
_x

From this we can conclude that the sum is 0. Is there a direct way of making sympy simplify this sum of roots?
Comment: I couldn't find much about simplifying symbolically for cubics and higher, but you can get a numeric approximation: `sum([root.eval_approx(20) for root in rr])`. [Documentation](https://docs.sympy.org/latest/modules/polys/reference.html#sympy.polys.rootoftools.ComplexRootOf.eval_approx).
Comment: @Maelstrom An exact evaluation is to be preferred, of course, ... and using `minimal_polynomial` it should be possible to extend the function `simplify` (or any other appropriate function) to make it capable of such simplifications. I might create an issue at the sympy project for this.
Comment: @Maelstrom see sympy issue #19726 (https://github.com/sympy/sympy/issues/19726)
Answer: The following function computes the rational number equal to an algebraic term if possible:
import sympy as sp

# try to simplify an algebraic term to a rational number
def try_simplify_to_rational(expr):
  try:
    float(expr) # does the expression evaluate to a real number?
    minPoly = sp.poly(sp.minimal_polynomial(expr))
    print('minimal polynomial:', minPoly)
    if len(minPoly.monoms()) == 1: # minPoly == x
      return 0
    if minPoly.degree() == 1: # minPoly == a*x + b
      a,b = minPoly.coeffs()
      return sp.Rational(-b, a)
  except TypeError:
    pass # expression does not evaluate to a real number
  except sp.polys.polyerrors.NotAlgebraic:
    pass # expression does not evaluate to an algebraic number
  except Exception as exc:
    print("unexpected exception:", str(exc))
  print('simplification to rational number not successful')
  return expr # simplification not successful

See the working example:
x = sp.symbols('x')
rr = sp.real_roots(x**3 - 3*x + 1)
# sum of roots equals (-1)*coefficient of x^2, here 0
print(sp.simplify(sum(rr)))
print(try_simplify_to_rational(sum(rr))) # -> 0

A more elaborate function computing also simple radical expressions is proposed in  sympy issue #19726.


Semantic UI Multiple Search Dropdown - onRemove not removing label

Question: I'm using semantic UI for a project and I just got into a little issue.
On my multiple search dropdown I want to be able to remove labels and do a callback function when doing so.
The callback function works fine but, the label is not being removed when clicked on the cross. It just stays there as if I selected it.
I'm also using Angular JS for this project, so here's the directive for the dropdown:
app.directive('dropdownSearchPersonalities', function () {
    return {
        restrict : 'A',
        link : function (scope, elem, attrs) {
            var personalitiesLength = scope.student.personalities.length;
            var studentPersonalities = [];

            for(var i = 0; i < personalitiesLength; i++) {
                studentPersonalities[i] = scope.student.personalities[i].name;
            }

            $(elem).dropdown({
                allowAdditions : true,
                onAdd: function (value) {
                    if(personalitiesLength) {
                        if($.inArray(value, studentPersonalities) != -1)
                            return;
                        else
                            scope.addPersonality(value, scope.studentId);
                    } else {
                        scope.addPersonality(value, scope.studentId);
                    }
                },
                onRemove: function (value, text, choice) {
                    scope.removePersonality(value, scope.studentId);
                }
            });

            $(elem).dropdown('set selected', studentPersonalities);
        }
    }
});

I repeat, the only thing that doesn't work is that the label is not removed, if I refresh the page the label that was meant to be removed is gone.
Here's an image of how it looks when trying to remove:

The cursor doesn't show up, but its actually over the cross icon.
Anyone has encountered this issue? How can I solve it?
Thanks a lot!
Comment: I didn't see anything in the documentation but can you try returning 'true' from the onRemove method after you call removePersonality?
Comment: @FerVargas did you find a solution? I am having a similar issue - the selected items remain in the UI but are actually removed when I get the values from the dropdown.
Answer: Use onChange, then in your inputs (event, data), the 'data' part will detect if you click on the 'x' or if you add a label. For example:
onChange (event, data) {
  this.setState({
    data: { ...this.state.data, [data.name]: data.value}
  });
}

The value automatically updates your array with all the options selected.


Page title block hidden on custom route, panel or view pages when content type is chosen in block visibility settings

Question: I defined a custom route in a custom module:
mymodule.overviewpage:
  path: '/mymodule-overview'
  defaults:
    _controller: '\Drupal\mymodule\Controller\PageOverviewController::content'
    _title: 'Overview'
  requirements:
    _permission: 'access content'

Here is the controller:
class PageOverviewController  extends ControllerBase {
  public function content() {
    return array(
      '#markup' => 'hello'
    );
  }

}

This route is working fine, I see the "hello" text when entering this path in my project but I do not see the page title. The page title "Overview" is used in the title tag in head of the HTML page but there is no page title block - it is not even rendered. Changing to Bartik theme I see the page title "Overview".
I know found out that the visibility of this block was set: there was a checkbox checked which defined the block to be hidden when on a node page of a special content type/ node bundle:

My question: why is the page title block not visible on panel or view generated pages or on custom routes? What should I add to avoid such a behavior? Is there a way to hide the block for special contenty types without hiding it elsewhere?
Answer: Because they are not a page of that node type. This filter doesn't just apply to node/*, it applies to all pages. And if there is no node object, the condition will always be false.
If you need something that is true on all non-node pages but for node pages only for a specific ype, you need to define your own condition plugin or use hook_block_access().
Comment: That is WOEFULLY not documented in the blocks ui. It is implicit from that (to me) that page title would be displayed everywhere, but where page types are concerned, only on the ones selected. If not, there needs to be a document on that - and a negate condition.


simplify expression with variable in denominator

Question: If I have an expression like this:
$3 - {\frac{48}{x^2}} = 0$
I should first rearrange it to this:
${\frac{3 -48}{x^2} = 0}$
In the example I am using this from, it is then simplified to:
${\frac{3x^2 -48}{x^2} = 0}$
And then:
$3x^2 -48 = 0$
I do not understand the last 2 steps.  I thought you would have to apply $x^2$ to both terms in the numerator, i.e. ${\frac{3x^2 -48x^2}{x^2}} = 0$.
Also How does $x^2$ get cancelled out this way when $x^2$ only appears in part of the term of the expression when it is like this:
${\frac{3x^2 -48}{x^2}} = 0$
I don't get how $x^2$ is cancelled out when it only appears on part of the term in the numerator.
Comment: Could it be that you are trying to find out when $f^\prime(x)=0$? If so, that will happen when the numerator is 0. That is, $f^\prime(x)=0$ when $3x^2-48=0$ but $f^\prime(x)\ne3x^2-48$.
Comment: Is your question about how to get that $3-\frac{48}{x^2}=\frac{3x^2-48}{x^2}$?
Comment: Yes that is the first part of my question and also how can $x^2$ be cancelled out when it only appears in one term of ${\frac{3x^2 -48}{x^2} = 0}$
Comment: @dagda1 Try multiplying both sides of the expression mathlove wrote with $x^2$; they are then in the same form and it's obvious that they are equal.
Answer: $3-{48\over x^2} \ne {3-48\over x^2}$.
This is because ${3-48\over x^2} = {3\over x^2}-{48\over x^2}$.
Clearly, $3\ne {3\over x^2}$.
Since $x^2 \ne 0$, ${3x^2-48\over x^2} = 0$ can be simplified to ${3x^2-48 = 0. x^2 = 0}$.
The solution would then be $x =\,\, ^+_-\,\, 4 $.


get data from session in an aspx page?

Question: I have class Bean,
then I creat some ob off Bean and add them to a list, then I convert list to an array.
I add this array into a session and use it in a aspx page, but cannot get data from session.
public Bean[] listAnswer()
    {
        SqlConnection con = new SqlConnection(@"Data Source=LEHUULOC-PC;Initial Catalog=WebThiTracNghiem;Integrated Security=True");
        con.Open();
        string sql = "SELECT * FROM tblCauhoi";
        SqlCommand com = new SqlCommand(sql, con);
        com.CommandType = CommandType.Text;
        SqlDataReader dr = com.ExecuteReader();
        List<Bean> Listbean = new List<Bean>();

        Bean[] result = null;
        while (dr.Read())
        {
            string macauhoi = (string)dr[0];
            string cauhoi = (string)dr[1];
            string cautraloi = (string)dr[2];
            string traloidung = (string)dr[3];
            //string dokho = (string)dr[4];
            Bean answer = new Bean(macauhoi, cauhoi, cautraloi, traloidung, "");
            Listbean.Add(answer);
            result = new Bean[Listbean.Count];
            result = Listbean.ToArray();
        }
        dr.Close();
        con.Close();
        return result;
    }

======================================
Bean bean = new Bean();
Bean[] answer = bean.listAnswer();
Session.Add("ANSWER",(Bean[])answer);

======================================

<form id="form1" runat="server">

this is hocsinh page
    <asp:Label ID="lblWelcome" runat="server"></asp:Label>
    <%

        foreach (var Bean in Session["ANSWER"])
        {
        }
    %>

</form>

but I receive error:  foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'
Answer: Try this:
<%
    Bean[] list = (Bean[])Session["RESULT"];
    if (list != null)
        foreach (var Bean in list)
        {
        }
%>

Answer: Bean has to be serializable and put it like this into your session:
Session.Add("ANSWER",bean);

read it like this:
var beans = Session["Answer"] as Bean[];

get data from session in an aspx page?


Editor specific command state

Question: I have created a command and a handler that interacts with text editors (objects implementing ITextEditor). For each editor that the handler interacts with I'd like to store some data that the handler has access to.
What is the best way to do this?
Information about my specific problem
My command modifies the selection of text of the active editor. When the command is executed I want to store information about the previous selection. Another command should be able read this information and restore the previous selection.
Thoughts and observations

If one handler instance was created for each editor that would solve my problem. Is there a way to achieve this?
I've looked at the source code of the Java editor, trying to understand how things work there. The editor stores references to action objects. Since I can't create new fields for my command I can't use the same approach.
I've looked at the <state> plugin.xml tag, but I don't understand how to get one piece of state for each editor. But maybe there is a way?
I could manually maintain a map from editor to state object, and maybe register a listener for when editors are opened and closed. But I would prefer if there was a simpler way, where I didn't have to do this myself.
Maybe actions (IAction) could be used? But aren't they an old mechanism that has been substituted by commands?
I could maybe manually set an IAction object which as an reference to the stack using the ITextEditor.setAction.
Comment: For Eclipse 4 you could perhaps use the MPart transient data (this can be accessed even for 3.x compatibility mode editors). Otherwise I think a Map is probably required. The old IAction interface doesn't help.
Answer: If you are using Eclipse 4 you could use the transient data of the MPart object associated with the IEditorPart.
To get the MPart from an IEditorPart use:
MPart part = editor.getSite().getService(MPart.class);

Map<String, Object> transientData = part.getTransientData();

You can store anything you like in the transient data, use a key unique to your handler for the map key. The data is discarded when the editor closes.

Editor specific command state


I don't know how to save Login Information of user on iPhone

Question: I am making app about google documents. but I don't know How to save Login Information
Document Folder ? Cache Folder ? Where save Login Information ?
Answer: The best option is to use the keychain.
There's example code at the Apple site or Buzz Anderson has some great code at his site
Alternatively you could use NSUserDefaults but that's less secure. The keychain is encrypted, user defaults are not (unless you encrypt before insertion but that's extra work)


How can $S=\{g_1^{e_1}\cdots g_t^{e_t}\}$ induce an hypercube?

Question: According to https://eprint.iacr.org/2022/1363.pdf at section 2.4, an hypercube can be induced by the equation 6:

Can someone explain to me how an hypercube can be induced? What are $g_1,\cdots, g_t$?
Comment: It would have been better had you bothered to include what the introduction of $S$ in the previous section instead of expecting your readers to track it down themselves: $S \subseteq \Bbb Z$ is any complete system of representatives for $\Bbb Z^∗_
m/\langle p\rangle$, and $p$ is an arbitrary prime. Still I see no introduction of the $g_i$. I suspect they are intended as the prime factorizations of the $h \in S$.
Comment: No, I can't really see how I can be more specific. I've already told you my *guess* as to what the $g_i$ are, and how they relate to the members of $S$. Do you not understand the concept of prime factorization? Do you really not see how a t-tuple of integers $\ge 0$ and $< \ell_i$ can be associated with the individual cubes in a box consisting of $\ell_1 \times \ell_2 \times \cdots \times \ell_t$ such cubes?
Comment: As for the hypercube (don't get stuck on the "cube" part - "hyperbox" would have been a better name), that is obvious from the representation: it is just identifying $h = g_1^{e_1}\cdots g_t^{e_t}$ with the point $(e_1, \dots, e_t)$, and identifying that point with a $1\times 1\times\cdots \times 1$ cube inside the hypercube $[0,\ell_1] \times \cdots \times [0,\ell_t]$.
Comment: @PaulSinclair could you be more specifiiic? I'll open a bounty on this one. I did not understand what you mean. For example, what are `g_i` and how can we select an hypercolumn
Answer: A hypercube structure seems fancy but it's just the cartesian product of the naturals that's bounded in each coordinate. We then place a convenient group structure on it to shunt symbols around. Lets look at a simple example.
Start with the set $S = \{(x,y) \in \mathbb{N}^2 \vert 0 \leq x < 3$,  $0 \leq y < 7\}$ an it's not hard to see that this set has $3 \times 7 = 21$ elements. This is refered to as the "number of plaintext slots".
Now we're going to add a group structure to the $x$ coordinate by consider it as the integers modulo $3$. We pick some generator of that group, say $g_1: (x,y) \rightarrow (x+1,y)$ so that we can write each element of it in the form $g_1^{e_1}$ with $0 \leq e_1 < 3$. We do the same thing with the $y$ coordinate but this time we reduce modulo $7$ and consider the generator of that group, say $g_2:(x,y) \rightarrow (x,y+1)$ so that we can write each element of that group in the form $g_2^{e_2}$.
Now that we have those two substructures we can consider the group generated by both  of them. Elements of this group will have the form $g_1^{e_1}g_2^{e_2}$ and this is because $g_1g_2=g_2g_1$ (check this!). This group is important enough to have enough so we're going to call it $h$, the hypercube group.
Now we don't have to stop here. We can generalize by adding a $z$ coordinate and bound it by $32$ so that we have a $3 \times 7 \times 32$ hypercube and we can define a group on the $z$ coordinate by considering the integers modulo $32$ which is generate by $g_3$ so that all elements will be of the form $g_3^{e_3}$ for $0 \leq e_3 < 32$ and doing the same thing as before we can generate a group from the elements $g_1^{e_1}g_2^{e_2}g_3^{e_3}$ which is an even fancier hypercube $h$.
And that's the whole thing. You just keep going by adding more coordinates that are bounded by $b$ and consider the integers modulo $b$ to generate a group, then add it into the mix to get a full group of transformations on the cube.
Comment: What is $g_1^{e_1}$  mathematically?
Comment: @GuerlandoOCs It's the $e_1$-th power of $g_1$, which is a generator of a the cyclic group of order $3$. The overall group is isomorphic to $\mathbb{Z}/3\mathbb{Z} \times \mathbb{Z}/7\mathbb{Z} \times \mathbb{Z} / 32\mathbb{Z}$ in which $g_1=(1,0,0)$ and $g_1^2=(2,0,0)$ and so on.


How to find if a record exist in PySpark in an efficient way?

Question: Given a PySpark Dataframe I'd like to know if for a column A exists a value (e.g. 5). The first approach would be to do something like
df.filter("A = 5")

but in this way the function would look for all the records that have that value, taking more time than expected. Instead if for example I know that I find the value in one of the first records I don't need to go ahead and continue iterating.
For example:
+---+
| A |
+---+
| 0 |
| 5 |
| 1 |
| 9 |
| 1 |
| 4 |
| 1 |
...
| 5 |
| 1 |

and suppose that it contains for thousands of records, I'd like to have a quick result as the 2nd record is 5, no need to check for the whole DF (of course there's no guarantee of performance because I might be unlucky and 5 is only the last record, but if I can save resources would be great!).
Any idea on how to achieve that?
Answer: An approach might be with
df.filter("A = 5").head()

With some tests I spotted a noticeable difference in execution time and the Spark engine seems to return in this way only the first occurrence that satisfies the condition.
So if it returns null the record doesn't exist (it will have to iterate through all the Datframe obviously), otherwise a Row object will be returned.


How to customize profile2 module profile edit form using template method?

Question: How to customize the profile edit form of the Profile2 module using a  template?
Profile2 has the main profile (admin/structure/profiles/manage/main), and it is set to provide a separate page for editing profiles (profile-main/1/edit).
In Drupal 7, for a content type such as faq, I can use a template to customized its edit form.
In template.php, I am using the following code:
function MYTHEME_theme(&$existing, $type, $theme, $path) {
  return array(
      'faq_node_form' => array(
      'arguments' => array('form' => NULL),
      'template' => 'node--faq--edit',
      'render element' => 'form',
  ),
  );
}

I then create node--faq--edit.tpl.php, where I can customize it.
What is the equivalent method I could use for a Profile2 profile edit form?
Answer: You should use form_id as theme key in hook_theme(), which is user_profile_form in the case.
function MYTHEME_theme(&$existing, $type, $theme, $path) {
  return array(
    'user_profile_form' => array(
      // …
    ),
  );
}

See Theme Profile2 Form, a support request opened for the Profile2 module.


Show that the bissectors of $\angle BHC$ and $\angle BFC$ meet on $BC$

Question: Given an acute triangle $\triangle ABC$ with orthocenter $H$. Let $D = BH \cap AC, E = CH \cap AB$ and $F = (AEDH) \cap (ABC) \neq A$. Show that the inner angle bisectors of $\angle BFC$ and $\angle BHC$ meet on the side $BC$.

It is easy to prove that the dotted ray passes through the midpoint of $BC$ and the antipode of $A$ in the $(ABC)$.
My first idea was to find $\angle CBF$ but that is a bit tough. So maybe drawing the perpendiculars from the meeting of the bissector of $\angle CHB$ with $BC$ to $FB$ and $FC$ may lead to something but it seems I need the forementioned angles.
Comment: After looking closer and closer i succeeded to find a short proof on the lines of the OP, i.e. by using the mid point of $BC$ and the antipode of $A$ on $\odot (ABC)$. After having the proof one can put together more related points, also some many points related to the common Apollonian circle of $F,H$ w.r.t. $B$ and $C$ and some (un)expected properties satisfied by the many points...  As a matter of taste, should i post as a second proof the minimal story, or also offer the bonus properties (after giving the short proof)?! Depending on this the presentation will differ...
Answer:
We use this fact that the bisector of $\angle BFC$ and Perpendicular bisector of BC meet on circumcircle of triangle BFC and the bisector of $\angle BHC$ and Perpendicular bisector of BC meet on circumcircle of triangle BHC. These two circle have common chord BC and the meeting points are both on perpendicular bisector of BC, that means bisectors of angles $\hat {BFC}$ and $\hat{BHC}$meet at G which is on BC.
Comment: BC  and its bisector are fixed  and F can be considered as affine transform of H. This requires that G to be be fixed .
Comment: sorry, it's not clear why $JI$ being the perpendicular bissector of $BC$ implies that $G = HI \cap FJ \in BC$.
Comment: ok I'm just not that familiar with projectivities. If you, or someone, could translate it to more synthetic argument it would help
Answer: Here is a possible solution which is chasing proportions. Using the given notation, the solution will live in the following picture:

We use the inversion in $A$ with power $AD\cdot AC = AE\cdot AB$, denoted by a star as upper decoration. So $B=E^*$ and $C=D^*$. (And the orthocenter $H$ is mapped to $H^*$, the projection of $A$ on $BC$.) The point $F$ which is on $(AED)\cap (ABC)$ is mapped to the finite point in the transformed intersection, which is an intersection of lines
$$
(AED)^*\cap(ABC)^*=(A^*E^*D^*)\cap(A^*B^*C^*)=(\infty BC)\cap(\infty ED)
\ ,
$$
so $F^*$ is the intersection of the lines $DE$ and $BC$. Now we will write some relations involving proportions, obtained from similar triangles related to inverted points, and Menelaus:
$$
\begin{aligned}
\frac{FB}{F^*E} &=
\frac{AF}{AE} =
\frac{AB}{AF^*}
&&
\text{ from }
&\Delta AFB &\sim \Delta AEF^*\ ,
\\
\frac{FC}{F^*D} &=
\frac{AF}{AD} =
\frac{AC}{AF^*}
&&
\text{ from }
&\Delta AFC &\sim \Delta ADF^*\ ,
\\
\frac{HB}{HC} &=
\frac{HE}{HD} =
\frac{BE}{CD}
&&
\text{ from }
&\Delta HBE &\sim \Delta HCD\ ,
\\
1 &=\frac{F^*E}{F^*D}\cdot\frac{CD}{CA}\cdot\frac{BA}{BE}
&&
\text{ from Menelaus in }
&\Delta AED &\text{ w.r.t. the line }F^*CB\ ,
\end{aligned}
$$
and get
$$
\frac{FB}{FC}
=
\frac{FB}{F^*E}\cdot
\frac{F^*E}{F^*D}\cdot
\frac{F^*D}{FC}
=\frac{AB}{AF^*}
\cdot\left(
\frac{BE}{BA}\cdot\frac{CA}{CD}
\right)\cdot
\frac{AF^*}{AC}
=\frac{BE}{CD}
=
\frac{HB}{HC}\ .
$$
Now use the angle bisector theorem in $\Delta FBC$ and $\Delta HBC$ to see that the bisectors in them from $F$, respectively $H$ hit $BC$ in the same point $X$.
$\square$

We are done, but here is a hint to the idea behind the proof. (Or consider it a "second proof", starting with a longer introductory story, and a shorter computation.)
For a (capital letter) point $Z$ in the plane denote by (its lower case pendant) $z\in\Bbb C$ its affix in the complex plane. (Do so for all letters, copy decorations.) The cross ratio "cr" of the four points $B,C;H,F$ has modulus $\frac{HB}{HC}:\frac{FB}{FC}$, so we want in fact to show that
$$
\operatorname{cr}(b,c;h,f):=\frac{h-b}{h-c}:\frac{f-b}{f-c}
$$
has modulus one. The cross ratio is invariant w.r.t. translations, rescaling, and inversion (i.e. w.r.t. homographic transformations), so we may replace the four points $(B,C;H,F)$ by "transformed" points obtained by some geometric inversion, e.g. the inversion w.r.t. $A$ used in the proof. So we pass to the tuple
$
(B^*,C^*;H^*,F^*)=(E,D;H^*,F^*)
$ which turns out to be simpler to handle.
Using the expression for $\frac{F^*E}{F^*D}$ from Menelaus, we are also done in some few lines:
$$
\begin{aligned}
\frac{HB}{HC}\cdot\frac{FC}{FB}
&=|\operatorname{cr}(b,c;h,f)|\\
&=|\operatorname{cr}(e,d;h^*,f^*)|=
\frac{H^*E}{H^*D}\cdot
\frac{F^*D}{F^*E}
=
\frac{AC\cdot\frac{BE}{BC}}{AB\cdot\frac{CD}{BC}}
\cdot
\frac{CD}{CA}\cdot\frac{BA}{BE}
\\
&=1\ .
\end{aligned}
$$
Comment: Yes! Unfortunately i could not use (known, or further easier) points on the Apollonian circle for $H$ w.r.t. $B,C$, and then show $F$ is also on that circle. The "known" points are $H$, then $X\in BC$ (mentioned above, so that $HX$ is the angle bisector from the problem), then $Y\in BC$ defined by $HY$ being the exterior angle bisector in $H$ or as $HY\perp HX$, and the reflection of $H$ w.r.t. $BC$, which is on $(ABC)$.
Comment: so $F$ and $H$ are on a same apollonian circle of $BC$
Comment: Well, the above proof is not really giving too much geometrical insight, i think i managed to get a quick proof by using ingredients suggested by the "Apollonian circle hint".
Answer:
With the ideas of sirous, we use barycentric calculus. The coordinates of $D$ and $E$ are
\begin{equation}
D\bigg(\frac{a^2+b^2-c^2}{2b^2},0,\frac{-a^2+b^2+c^2}{2b^2}\bigg),\quad E\bigg(\frac{a^2-b^2+c^2}{2c^2},\frac{-a^2+b^2+c^2}{2c^2},0\bigg)
\end{equation}
The circumcircle $(ABC)$ has equation $-a^{2}yz-b^{2}xz-c^{2}xy=0$ and $(AED)$ has $-a^{2}yz-b^{2}xz-c^{2}xy+\Big(\frac{a^2-b^2+c^2}{2}y+\frac{a^2+b^2-c^2}{2}z\Big)(x+y+z)=0$ whose intersection $F\neq A$ is
\begin{equation}
F\Big(a^2\big(a^2+b^2-c^2\big)\big(a^2-b^2+c^2\big):-\big(-b^2+c^2\big)\big(a^2+b^2-c^2\big)\big(-a^2+b^2+c^2\big):\big(-b^2+c^2\big)\big(a^2-b^2+c^2\big)\big(-a^2+b^2+c^2\big)\Big)
\end{equation}
The bisector of $BC$ is $y-z=\frac{-b^2+c^2}{a^2}x$ whose below intersection with $(ABC)$ is $U\big(-a^2:b(b+c):c(b+c)\big)$.
The lines $BC$ and $UF$ intersects on $G_1\Big(0:\big(a^2+b^2-c^2\big)c:\big(a^2-b^2+c^2\big)b\Big)$.
The orthocenter is $H\Big(\big(a^2+b^2-c^2\big)\big(c^2+a^2-b^2\big):\big(b^2+c^2-a^2\big)\big(a^2+b^2-c^2\big):\big(c^2+a^2-b^2\big)\big(b^2+c^2-a^2\big)\Big)$ and $(HBC)$ is $-a^{2}yz-b^{2}xz-c^{2}xy+\big(b^2+c^2-a^2\big)x(x+y+z)=0$ and the intersection of this circle with the bisector of $BC$ is $V\big(-a^2:a^2+bc-c^2:a^2+bc-b^2\big)$.
The lines $BC$ and $HV$ intersects on $G_2\Big(0:\big(a^2+b^2-c^2\big)c:\big(a^2-b^2+c^2\big)b\Big)$.
We have $G_1=G_2$ and the demostration is done.
Answer: Note that $\angle FBE = \angle FCD$ and $\angle BEF = 180^\circ - \angle FEA = 180^\circ - \angle FDA = \angle CDF$. It follows that $\triangle BEF \sim \triangle CDF$. Therefore $$\frac{BF}{CF} = \frac{BE}{CD}.$$
On the other hand, $\triangle BEH \sim \triangle CDH$, hence $$\frac{BE}{CD} = \frac{BH}{CH}.$$
Therefore $$\frac{BF}{CF} = \frac{BH}{CH}.$$
We are done by angle bisector theorem: the bisectors of angles $BFC, BHC$ intersect the segment $BC$ at the point $X$ satisfying $$\frac{BX}{CX} = \frac{BF}{CF} = \frac{BH}{CH}.$$
Answer: Here is yet on other proof, essentially using the observations (qualified as simple) of the OP regarding the mid point of $BC$ and the antipode of $A$ to conclude. These points and some related points should be introduced first, so in order to separate notations from arguments, i will restate, then give the quick proof in a minimal picture. After the proof, some interesting bonus properties in the given constellation of points may be (or may be not) interesting. A list of these properties with hints to show them is provided, and for the convenience of the reader an involved picture is then also given. Well, please ignore this bonus if it feels off-topic.

We restate and introduce notations.
Proposition: Let $\triangle ABC$ be a triangle with orthocenter $H$, circumcenter $O$. Let $H^*=AH\cap BC$, $D = BH \cap AC$, $E = CH \cap AB$ be the feet of the heights in the given triangle.
Let $F\ne A$ be the second point of intersection of the circles $(AEDH)$ and  $(ABC)$.
We furthermore construct the following points:
Let $M$ be the mid point of the side $BC$, let $K\in AH\cap (ABC)$ be the reflection of $H$ w.r.t. $BC$, let the side bisector $OM$ of the side $BC$ intersect $(ABC)$ in the points $Q$ and $V$, so that $A,V$ are the same side w.r.t. $BC$ and $AQ$ bisects $\hat A$. Let $A'$ be the antipode of $A$ in the circle $(O)=(ABC)$, so $A'=AO\cap FHM$.
Let $X$ be the intersection of the
inner angle bisectors of $\sphericalangle BFC$, which is $FQ$, and of $\sphericalangle BKC$, which is $KV$.
Show that $X\in BC$ .
Note: Since $\Delta BKC$ and $\Delta BHC$ are reflected in $BC$, the angle bisector of $\sphericalangle BKC$ also passes through $X$, which is mot-a-mot is the posted question.
Note: As mentioned by the OP, $A'$ is on $HM$, since for instance $H^*M$ is half of and parallel to $KA'$, so it is the mid line in $\Delta HKA'$. The point $F$ is also on the line $HA'$ since $\widehat{AFH}=90^\circ$ in the circle $(AFEHD)$ with diameter $AH$ and $\widehat{AFA'}=90^\circ$ in the circle $(ABC)$ with diameter $AA'$.

The picture is as above, and now we can start the answer:
Proof: Apply Pascal's theorem in the (degenerated) hexagon $A'FQQVK$.
$\square$
Details: The three colinear points from Pascal's Theorem are explicitly in this special case $A'F\cap QV=M$, $FQ\cap VK=X$, and $QQ\cap KA'$. The latter point is the point at infinity lying on the two parallel lines $QQ$ (tangent in $Q$ at the circle $(ABC)$) and $KA'$, and thus on each further line having their common direction. The line $BC$ is such a line, and it contains $M$. So it contains also $X$.
Comment: we have a winner! As soon as I can I will award you with the bounty
Comment: the fact that $KXV$ are colinear is also important I didn't notice it first but it is easy to prove


Show names of positional arguments inlayed

Question: I've recently been doing some programming in Rust using Clion. This provides a utility whereby when you pass positional arguments to a function it will show you which argument will pick up each value (as if you had passed them in as keyword arguments) see below:

I've found this to be a very nice feature as it's made code a fair bit more readable and prevented me making a couple of stupid mistakes. Therefore, I'd love to have this functionality in PyCharm for programming Python, does anyone know of a plugin which can do this?
Answer: I think the Python Inlay Params plugin does what you want. It adds inlay hints both for callable parameters, values, and for types on variables.
Here's a convenient snippet transcribed from the demo for testing:
class Dimens:
    width: int
    height: int

    def __init__(self, width, height):
        self.width = width
        self.height = height

a = Dimens(1, 2)

And a screenshot in action using PyCharm 2022.1 Pro

See the Settings instructions on the Python Inlay Params GitHub's page. The above snippet worked for me using the default settings after installing the plugin.

For pytest users there's also the Pytest Parametrize Inlay Hint.
Just for type hints and not variables (thus not for parameters or values) there's also Python Inlay Hints.
There aren't currently any other plugins for PyCharm on JetBrains marketplace that do what you want.

It should be mentioned that using PyCharm without plugins you can already get values for parameters shown in the editor just using the debugger. For example with the following snippet:
def my_func(a: int, b: str):
    c = a
    c = c + 1
    print(str(a), b)
    return

my_func(1, 'b')

During debugging the values will be shown alongside the variables and the parameters, although not embedded in the code of the signatures themselves. As shown in the screenshot:

To configure the shown functionality go to File > Settings > Build, Execution, Deployment > Debugger > Data Views and under Editor check Show values inline. See the PyCharm documentation View values inline.
Comment: @Pioneer_11 Yes it's working for me with functions, [here's a screenshot](https://i.stack.imgur.com/XPPl4.png). If it's not working for functions verify the [plugin's settings as shown on GitHub](https://github.com/WhiteMemory99/Intellij-Python-Inlay-Params#settings) (I had already linked to the settings in the post.) The previous screenshot in this comment shows it working with default settings and where the settings are.
Comment: Python inlay params looks perfect. However, I have added it to my environment and it doesn't appear to be working. Is there any particular setup which needs to be performed?
Comment: I am aware of the ability to use the debugger. However, I often have to work with numpy and matplotlib which can have confusing positioning of arguments and where the cost of rerunning or running in debug mode is high. Thus my desire for something which will show arguments while coding.
Comment: @Pioneer_11 I edited the question, the plugin worked for me right after installation without having to restart the IDE and just using the default pre-configured settings (If it doesn't work: try restarting the IDE, invalidating caches, creating a new project, check manually that the settings are properly configured, and verify what IDE version you're on). See the [supported versions](https://plugins.jetbrains.com/plugin/19538-python-inlay-params/versions#tabs) it should work on PyCharm up to the latest version. If it still doesn't work you should post your system spec on the GitHub issue page.
Comment: @Pioneer_11 I just tested it again and restarting the IDE might be necessary to get it to work.
Comment: could I please check what version you're using. I'm currently on 0.1.4, apparently anything more recent requires pycharm 213 or above, (I am currently on 212 and it appears that 213 is not currently stable)
Comment: @Pioneer_11 I'm using PyCharm 2022.1 the plugin installes with 0.3.1 and starts working immediately (not requiring IDE restart). If you're on PyCharm 2021.2 yes you'll get the plugin version 0.1.4. Notice that your IDE version PyCharm 2021.2 is the lowest supported version and only 1 plugin release supports it. Your best chance is just updating the IDE to any later version in which case you'll get latest plugin version.
Comment: @Pioneer_11 [your PyCharm is 4 versions behind](https://www.jetbrains.com/pycharm/download/other.html) and almost 1 year old. You should update because those intermediate versions are all stable by now (barring one or the other version specific bug). If you update to PyCharm 2022.1 I can guarantee I haven't found any bugs or instability with it.
Comment: are you able to get it working with functions? I have updated my version of my pycharm and it now works perfectly with classes but I still cannot get it to work with functions.


How to model a curve with multiple shapes?

Question: I have the following conceptual model:

I want to be able to create an inferential model (e.g., NLM, GAMM, etc.) that can predict the above conceptual model.
To do so, I need my predictive model to account for the curves/structure of the conceptual model.
I don't know how to do that...
I'd seen elsewhere that the assymptotic part of the model could be graphed as $f(x) = b[1 - exp(ax)]$ , where $b$ is the asymptote and $a$ controls the rate of approach to the asymptote.
I also know a 3rd or 4th order polynomial might capture some of the oscillation behavior.
Can anyone help me construct a mathematical model that overlays my theoretical curves?
Theoretically, I want to capture i) the different ascent patterns, ii) the magnitude of the peak, iii) the magnitude of the subsequent dip, and iv) late-term rate of approaching an equilibrium.
Answer: You might want to look at Second order LTI systems. Basically the functions of your graph can be modelled by a differential equation of second order, for which the solution looks like one of these three.
For instance the "long lag" one can be modelled by a function that is $y(t) = A\exp(-t/\tau)\sin(\omega_pt+\phi)$
It corresponds to the solution of an equation of the form $\omega_0^2y'' + 2\xi\omega_0y' + y = 0$ where $\Delta = 4\omega_0^2(\xi^2-1) <0$
In this case you can even calculate the overshoot of your signal with respect to the final value. The two other cases correspond to $\Delta = 0$ or $\Delta >0$.
There is a lot of resources on LTI models online so you'll find more precise info there.
Comment: Yes they are just constants. Basically their value will influence the form of the solution. $\xi$ is the damping ratio and $\omega_0$ is the natural pulsation. The damping is what influence the look of the oscillations (and their number). The higher it is, the lesser the oscillations.
Comment: Thanks! +1.  I'll start reading [here](http://www.dartmouth.edu/~sullivan/22files/2nd%20order04.pdf). Could you define/explain any of the variables you've listed (e.g., ξ, ω, etc.) -- or are these just constants??
Comment: If you take the function $y(t) = A\exp(-t/\tau)\sin(\omega_pt+\phi)$ for instance then $\frac{1}{\tau} = \xi$ and $\omega_p = \omega_0\sqrt{\xi^2 -1}$


Multinomial Probability Exercise

Question: I have this problem:
Among 30 students in a group, 6 students received grade "5" for the exam, 10 students - "4", 9 students - "3", the rest - "2". Find the probability that 3 students, called to the blackboard, got grade "2" for the exam.
So I easily solved it because it's a multinomial distribution.
<code>|grade| 5   |  4   |  3  |  2  |
--------------------------------
|prob | 6/30| 10/30| 9/30| 5/30|
</code>
x2 = number of students who got grade "2"
P(x2 = 3) = 3!/(0!0!0!3!) * (6/30)^0 (10/30)^0 (9/30)^0 (5/30)^3 = (5/30)^3 = 0.0046
But the correct answer is 0.002. Is it a mistake or am I wrong?
Answer: Hint: Think of differences between sampling with and without replacement.
Answer: Okay, we have a 3 spot, _ _ _
all the spot has to be filled by only those who obtained grade "2"
since, we not concerned about other graded student, we only take 5 students with grade "2".
$$P(first spot)= 5/30$$
$$P(second spot)= 4/29$$
$$P(third spot)= 3/28$$
$$result = (5/30)*(4/29)*(3/28)=(1/406)=0.002463054187$$
Comment: since, 3 students were called to the blackboard. I meant those 3 spot for those 3 student position.
Comment: I think the original question should be "Find the probability that 3 students, called 3 students to the blackboard, got grade "2" for the exam." and your answer is correct. If called more than 3 students, for example 4, then your answer is incorrect. So original question is not clear.
Comment: There is no "we have a 3 spot" in OP. "called to the blackboard" means "we have a 3 spot"?

Multinomial Probability Exercise


HTTPS endpoint of Azure event hub

Question: I am using service that can only send messages using webhook. The only thing I can set up in that webhook are HTTP endpoint, user name and password (you can see it on the screenshot below). I would like to send messages to my event hub, but I don't know how to find its HTTP endpoint. The only thing I could find was SAS Endpoint.
Comment: Azure Event Hub client sdk provide ways to connect to the Event Hub namespace via connection string and the name of the Event hub. There is no direct https endpoint to that specific Event Hub. You may need to write a function app which sends messages to the Event Hub, and in the above config screen provide your function app https url.
Answer: Event Hubs offers a REST API that allows you to perform a subset of the  operations supported by its AMQP API.  Publishing basic events via REST is possible and would use the endpoint: https://{servicebusNamespace}.servicebus.windows.net/{eventHubPath}/messages.
The full set of documentation for the REST API can be found here, and the specifics for sending events here.
Comment: I'm not sure if I understand it correctly, but to use it I need to use SAS token as a authorisation method. The only parameters that I can use for authorisation are User name and password. Should I insert SAS token to the HTTP endpoint?
Comment: The REST endpoints do not support basic authentication; if you're not able to add custom headers so that you can pass the needed token, then the suggestion that Aanand made for standing up your own HTTP endpoint and then forwarding the event is going to be your best bet.
Comment: I have discovered that it is possible to use token authorisation in this webhook. However I have tried both primary and secondary key from SAS Policy and it didn't work. Do you know how I can pass sas token in http message?
Comment: They're passed via the standard HTTP header mechanism; the first link that I included above has authorization details.

HTTPS endpoint of Azure event hub


Rank-$2$ $\Bbb Z$-module invariant under action of root of unity

Question: Assume $\epsilon =e^{2\pi i /n}$ -some root of unity. For which $n$ it is possible to find $x=re^{i\phi} \in \mathbb{C}$ such that $\epsilon (\mathbb{Z} + re^{i \phi}\mathbb{Z}) \subset (\mathbb{Z} + re^{i \phi}\mathbb{Z}) $?
But any comments, as usual , will be very helpful. Thanks!
Comment: Have you found many values of $n$ for which this works? The ones I can think of are all relatively small. Geometrically this is about plane lattices stable under a rotation of finite order, and I think the usual suspects give all of them. Need to recall the argument...
Comment: @JyrkiLahtonen: thank you for response, i will pay attention to geometrical side also
Answer: You're asking for two-dimensional $\Bbb Z$-lattices which have some rotational symmetry. Ultimately you should be able to see that $r=1$ or else $\epsilon\not\in \Bbb Z + x\Bbb Z$. In fact in this case it must be that we can choose $\phi$ generated by $\epsilon$. But your question is actually even simpler than that, since you want this to be closed under the $\Bbb Z[\epsilon]$ action, you need that your module is actually a rank-2 module over $\Bbb Z$, which means it's just going to be $\Bbb Z[i]$ or $\Bbb Z[\omega]$ where here $\omega$ is a primitive third root of 1, since these are the only degree $2$ roots of unity aside from the sixth roots of unity, but we know that $-\omega$ is such a root, so it's already within $\Bbb Z[\omega]$. This can be seen in a myriad of ways, but I think the simplest is just to note that the degree of a root of unity is $\phi(n)\ge \sqrt{n/2}$.
Comment: Please excuse the picky correction, but the sixth roots of unity also are quadratic over $\Bbb Q$.
Comment: @Anna if that were the case then your rank would be off, remember you have a very strong assumption that this is rank $2$ as a $\Bbb Z$-module:  if $e^{i\phi}$ is not a root of unity, then $1, \epsilon, e^{i\phi}$ are all linearly independent over $\Bbb Z$, hence the rank is at least 3.
Comment: @Anna Linear independence of such things is classical, but one easy way to see is that $a+b\epsilon$ as a transformation of the plane is affine, it rotates, dilates, then translates, whereas $e^{i\phi}$ is a pure rotation. But then in order for $a+b\epsilon = e^{i\phi}$, i.e. linear dependence, we'd need that these induce the same isometry, but this is only possible if it fixes $0$, i.e. there is no translation, $a=0$, and does not dilate, i.e. $b=1$, hence $\epsilon = e^{i\phi}$ in the case there is a dependence.
Comment: @Lubin of course you are right. Enough years in number theory to not bother telling an odd and twice an odd apart in cyclotomy and not enough to remember they still matter!
Comment: @AdamHughes, can you give some comments on your observation that  $\phi$ can be chosen as generated by $\epsilon$ ($r=1$ is trivial, and other explanations are clear). You say, that from $\mathbb{Z} \oplus \mathbb{Z} \epsilon  \subset \mathbb{Z} \oplus \mathbb{Z} e^{i\phi}$ it follows that they are equal, am i right? Thank you)
Comment: @AdamHughes is there a simple reason for why $\epsilon$ can not be expressed as $\mathbb{Z}$-linear combination of $1,e^{i\phi}$ in the case $e^{i\phi}$, $\epsilon$ doesn't coincide?
Comment: @AdamHughes, thank you for very detailed answer
Comment: @Anna glad to help. Keep in mind you should still try and work out the details to be sure you understand things completely, and best of luck with your studies
Comment: @AdamHughes, i will, thank you so much! But I'd like to make a small remark to your answer: $e^{-4\pi i/3}=1+ e^{2\pi i/3}$, and therefore your argument might seem a bit incomplete.
Comment: @Anna that is correct, and part of why I said you should try and work out the details yourself. Working out the associated lemmata for the main result is good practice. :)
Comment: @Anna and here's a more algebraic way:  if $e^{i\phi}$ is not a root of unity, then it will generate an infinite degree extension of $\Bbb Q$ in particular $\Bbb Z[e^{i\phi}]$ is not a finite rank $\Bbb Z$-module. SImilarly if it is a root of unity what can you conclude?
Comment: @AdamHughes, $\mathbb{Z}[a+b\epsilon]=\mathbb{Z}[\epsilon]$ is f.g. $\mathbb{Z}$-module, with rank less than degree of root unit.
Comment: @AdamHughes,but  roots of unity are not the only algebraic integers with the value of norm equals to $1$, so that $\mathbb{Z}[e^{i\phi}]$ is not that simple..
Comment: @Anna but they are for rank $2$, you have to keep that in mind, that's the most essential part of this question start to finish. The key to addressing this problem is seeing all the info **together** not just one aspect at a time.
Comment: @AdamHughes, "one aspect at a time" -- is definitely for me today! But $\mathbb{Z}+\mathbb{Z}[e^{i\phi}]$ need not to coincide with $\mathbb{Z}[e^{i\phi}]$ in my question! It only should be $\epsilon$-invariant. Thank you again for very long and useful discussion!


Fork creates a new process that is exactly the same as its parent

Question: From the assumption made in the title of my question "Fork create a new process that is exactly the same as its parent". I am wondering how a fork is really made by the operating system.
Considering a heavy process (huge RAM footprint) that fork itself to accomplish a small task (list the files into a directory). From the assumption, I expect that the child process will be as big as the first one. However my common sense tells me that it cannot be the case.
How does it work in the real world?
Comment: https://en.wikipedia.org/wiki/Copy-on-write might be helpful here
Comment: @nowox the "man 2 fork" can help you a lot.
Comment: A mechanism called Copy-on-Write(COW) is employed.

This means that read-only portions of memory (those memory pages with just the R(ead) or (e)X(ecute) bit set) are actually shared between the 2 processes.

For memory that is writable, a private copy of a page is created for the child process only if it tries to write to it.
Comment: `man 2 vfork` is interesting for historical rationale.
Comment: @Jasper Are you saying that the executable code is located in RAM and both processes share the same memory space?
Answer: As others mentioned in the comments, a technique called Copy-On-Write mitigates the heavy cost of copying the entire memory space of the parent process. Copy-on-write means that memory pages are shared read-only between parent and child until either of them decides to write -- at which point the page is copied and each process gets its own private copy. This technique easily prevents a huge amount of copying that in a lot of cases would be a waste of time because the child will exec() or do something simple and exit.
Here's what happens in detail:
When you call fork(2), the only immediate cost you incur is the cost of allocating a new unique process descriptor and the cost of copying the parent's page tables. In Linux, fork(2) is implemented by the clone(2) syscall, which is a more general syscall that allows the caller to control which parts of the new process are shared with the parent. When called from fork(2), a set of flags are passed to indicate that nothing is to be shared (you can choose to share memory, file descriptors, etc - this is how threads are implemented: by calling clone(2) with CLONE_VM, which means "share the memory space").
Under the hood, each process's memory page has a bit flag that is the copy-on-write flag that indicates whether that page should be copied before being written to. fork(2) marks every writeable page in a process with that bit. Each page also maintains a reference count.
So, when a process forks, the kernel sets the copy-on-write bit on every non-private, writeable page of that process and increments the reference count by one. The child process has pointers to these same pages.
Then, every page is marked read-only so that an attempt to write to the page generates a page fault - this is needed to wake up the kernel so that it has a chance of seeing what happened and what needs to be done.
When either of the processes writes to a page that is still being shared, and thus is marked read-only, the kernel wakes up and attempts to figure out why there is a page fault. Assuming the parent / child process is writing to a legit location, the kernel eventually sees that the page fault was generated because the page is marked copy-on-write and there is more than one reference to that page.
The kernel then allocates memory, copies the page into the new location, and the write can proceed.
What is different across forks
You said that fork(2) creates a new process that is exactly the same as its parent. This is not quite true. There are several differences between the parent and the child:

The process ID is different
The parent process ID is different
The child's resource usage (CPU time, etc) are set to 0
File locks owned by the parent are not inherited
The set of pending signals on the child is cleared
Pending alarms are cleared on the child

About vfork
The vfork(2) syscall is very similar to fork(), but it does absolutely no copying - it doesn't even copy the parent's page tables. With the introduction of copy-on-write, it's not as widely used anymore, but historically it was used by processes that would call exec() after forking.
Naturally, attempting to write to memory in the child process after a vfork() results in chaos.
Answer: When a process forked, the child process use the same page table as its parent util parent or child write to its space!So


No prometheus in Gitlab Omnibus

Question: Setup: Ubuntu 14.04 with all recent updates,
Gitlab Omnibus version 11.7.3 (latest)
~$ sudo grep prometheus /etc/gitlab/gitlab.rb

prometheus_monitoring['enable'] = true
prometheus['enable'] = true
prometheus['listen_address'] = ':9090'

The problem - browser cannot connect to http://localhost:9090, and logs are empty.
$ curl http://localhost:9090
curl: (7) Failed to connect to localhost port 9090: Connection refused

$ sudo gitlab-ctl tail prometheus
==> /var/log/gitlab/prometheus/state <==

==> /var/log/gitlab/prometheus/current <==

sudo netstat -tunlp does not show port 9090
However, the prometheus process seems to be running:
$ ps ax | grep prometheus
 1358 ?        Ss     6:32 runsv prometheus
 1377 ?        S      0:35 svlogd -tt /var/log/gitlab/prometheus
 6935 ?        Ssl    0:02 /opt/gitlab/embedded/bin/gitlab-workhorse -listenNetwork unix -listenUmask 0 -listenAddr /var/opt/gitlab/gitlab-workhorse/socket -authBackend http://localhost:8080 -authSocket /var/opt/gitlab/gitlab-rails/sockets/gitlab.socket -documentRoot /opt/gitlab/embedded/service/gitlab-rails/public -pprofListenAddr  -prometheusListenAddr localhost:9229 -secretPath /opt/gitlab/embedded/service/gitlab-rails/.gitlab_workhorse_secret -config config.toml
25394 pts/0    S+     0:00 grep --color=auto prometheus

Forgot to add, nginx, bundled with Gitlab is disabled. I use another nginx, installed from repositories.
Also tried restarting prometheus - no luck.
~$ sudo gitlab-ctl restart prometheus
ok: run: prometheus: (pid 32380) 0s

~$ curl -I http://localhost:9090
curl: (7) Failed to connect to localhost port 9090: Connection refused

Update.
But now prometheus logs are not empty! Somehow its group was deleted.
Answer: After restarting, prometheus logs were not empty! Somehow group gitlab-prometheus was deleted. After restoring the group, everything Ok.

No prometheus in Gitlab Omnibus


Dimension Error WIth Tensorflow 2D Convolutional Layer

Question: I'm trying to work with the SVHN Dataset in order to develop a Deep Digit Recognition App
SVHN Dataset Link
I am using the .mat files and in my code the pickle file contains a dictionary of the train test and test set which have been created with the help of the respective .mat files.
I am trying to create a CNN model which has ~3 CNN Layers along with max pooling Layers and a Fully Connected Layer with Dropout and Decaying learning Rate.I'm getting stuck with some matrix dimensions errors.
<code>filename='SVHN.pickle'

with open(filename,'rb') as f:
other=pickle.load(f)

train_data=other['train_dataset']

del other

train_dataset=train_data['X'].astype(np.float32)
train_labels=train_data['y']
train_dataset=np.reshape(train_dataset,(32,32,73257,-1))
print(train_dataset.shape)
#print(train_labels)

classes=10

batch_size=32

num_steps = 1500

graph=tf.Graph()

'''Placeholder for the data'''
data_placeholder=tf.placeholder(tf.float32,shape=(None,batch_size,batch_size,3))
label_placeolder=tf.placeholder(tf.float32,shape=(classes))

'''Variable for Weights and Biases'''
#1024 is for the number of nodes in each hidden layer

layer1_weights=tf.Variable(tf.truncated_normal([batch_size,32,32,512]))
layer1_biases=tf.Variable(tf.zeros([512]))
#tf.cast(layer1_weights,tf.float64)
#tf.cast(layer1_biases,tf.float64)

layer2_weights=tf.Variable(tf.truncated_normal([batch_size,512]))
layer2_biases=tf.Variable(tf.zeros([512]))

layer3_weights=tf.Variable(tf.truncated_normal([batch_size,512]))
layer3_biases=tf.Variable(tf.zeros([512]))

layer4_weights=tf.Variable(tf.truncated_normal([batch_size,512]))
layer4_biases=tf.Variable(tf.zeros([512]))

def layer_multiplication(data_input_given):

    #Convolutional Layer 1

    CNN1=tf.nn.relu(tf.nn.conv2d(data_input_given,layer1_weights,strides=[1,1,1,1],padding='SAME')+layer1_biases)

    #Pooling Layer

    Pool1=tf.nn.max_pool(CNN1,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')

    #second Convolution layer

    CNN2=tf.nn.relu(tf.nn.conv2d(Pool1,layer2_weights,strides=[1,1,1,1],padding='SAME'))+layer2_biases

    #Second Pooling

    Pool2 = tf.nn.max_pool(CNN2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    #Third Convolutional Layer

    CNN3 = tf.nn.relu(tf.nn.conv2d(Pool2, layer3_weights, strides=[1, 1, 1, 1], padding='SAME')) + layer3_biases

    #Third Pooling Layer

    Pool3 = tf.nn.max_pool(CNN3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    #Fully Connected Layer

    FullyCon=tf.reshape(Pool3,[-1,32,32,512])

    FullyConProcess=tf.nn.relu(tf.matmul(FullyCon,layer4_weights)+layer4_biases)

    dropout = tf.nn.dropout(FullyConProcess, 0.4)

    return dropout

gloabl_step = tf.Variable(0, trainable=False)

decay_rate=tf.train.exponential_decay(0.1,gloabl_step,4000,0.96,staircase=False,)

train_input=layer_multiplication(train_dataset)

loss=(tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=label_placeolder,logits=train_input))
                                   + 0.01 * tf.nn.l2_loss(layer1_weights)
                                   + 0.01 * tf.nn.l2_loss(layer2_weights)
                                   + 0.01 * tf.nn.l2_loss(layer3_weights)
                                   + 0.01 * tf.nn.l2_loss(layer4_weights)
      )

optimizer = tf.train.GradientDescentOptimizer(name='Stochastic', learning_rate=decay_rate).minimize(loss,global_step=gloabl_step)

train_prediction = tf.nn.softmax(train_input)

with tf.Session(graph=graph) as session:
    tf.global_variables_initializer().run()
    print('Initialized')

    for step in range(num_steps):
        offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
        batch_data = train_dataset[offset:(offset + batch_size)]
        batch_labels = train_labels[offset:(offset + batch_size)]

        #print(batch_data)
        #print(batch_labels)

        feed_dict = {data_placeholder:batch_data, label_placeolder:batch_labels}
        _, l, predictions = session.run(
            [optimizer, loss, train_prediction], feed_dict=feed_dict)
        if (step % 500 == 0):
            print('Minibatch loss at step %d: %f' % (step, l))
            #print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))
            #print('Validation accuracy: %.1f%%' % accuracy(
                #valid_prediction.eval(), valid_labels))
    #print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))
</code>
Here is the error which I'm getting

ValueError: Dimensions must be equal, but are 1 and 32 for 'Conv2D' (op: 'Conv2D') with input shapes: [32,32,73257,1], [32,32,32,512].

I have tried to fiddle with the dimensions but to no avail.
I'd be highly obliged if anyone can correct my error and tell me how can i avoid this error in the future.
Answer: You need to define weights shape properly, change all the weights shape as follows.
<code># weights shape should be [filter_height, filter_width, in_channels, out_channels]
# suppose filter size (3, 3), in_channel = 3 (RGB image input)
layer1_weights=tf.Variable(tf.truncated_normal([3,3,3,512]))

# here for fully connected weights_shape [in_channels, out_channels]
# in_channels last dimension of the previous layer's output
layer2_weights=tf.Variable(tf.truncated_normal([512, 512]))

# Also the placeholders
data_placeholder=tf.placeholder(tf.float32,shape=(None,input_height,input_width,3))
label_placeolder=tf.placeholder(tf.float32,shape=(None, classes))
</code>
Comment: Is the shape of the bias variable proper? And by out channels you refer to the hidden nodes right?
Comment: yahh shape of bias variable is proper. `[out_channels]` of the weights
Comment: I made the changes in the same format with a little modification and now i'm getting errors related to memory allocation.Would it be possible for you to give your email id so i can show you the error with the related code?


R glm for censored data

Question: I want to know if there is a significant difference in a blood biomarker concentration between 2 populations (population 1 = healthy individuals - population 2 = sick individuals). I need to control for the factor 'region'.
My issue is that the distribution of population 2 is not normal (data are censored following the upper detection limit by the lab device) as shown on these plots:

With a normal distribution I would use this model in R:
<code>m <- glm(blood.biomarker ~ status + region + status*region, data=f, family="gausian") # status = healthy or sick
summary(m)
emmeans(m, list(pairwise ~ status), adjust = "tukey")
</code>
I am a bit confused regarding the model or the glm family I should use in this case.
I also have a similar situation but with 3 groups (1 group has a normal distribution and 2 groups have a censored distribution). How to deal with this?
Comment: If you have censored data then you need survival analysis. vanilla linear models will not do.
Comment: In survival analysis we assume that censoring is independent which is not the case here
Answer: The blood biomarker concentration measurements are censored because of the upper detection limit (at 2,500 judging from the plots).
You can use ordinal regression (aka proportional odds regression) to model the data. You can also do a Wilcoxon rank-sum test to compare populations 1 and 2 or the Kruskal-Wallis test to compare more than two populations. But with the tests you cannot include additional covariates (such as region) and in any case ordinal regression generalizes these tests.
Alternatively, you can use tobit regression.
Keep in mind that the censoring implies some loss of information. For example, you can't learn much about the upper quantiles of the blood biomaker in population 2, other than they are ≥ 2,500. Similarly, you cannot do precise inference (say a 95% two-sided confidence interval) for the population 2 mean.
Here are some relevant threads/links:

Biostatistics for Biomedical Research Sections 7.3.1 and 7.6.2 analyze data censored at an upper detection limit of 2,5000, just as in your case.
Tobit models and Ordinal logistic regression by the UCLA Stats Help.
What regression approach would suit zero-inflated data that is censored at a fuzzy threshold?
Explanation of a censored regression model

Or search for censored regression on Cross Validated.
Answer: Possibly you might figure out some distribution and apply some censurized estimation method.
But, in this case, a single regressor (the groups), it might be easier to perform a permutation test.

R glm for censored data


cant get the param route angular 6

Question: I'm trying to get the [param] from url, and get some information throw a service with this param, and then (ONLY then) go to another page.
Chome URL: http://localhost:4200/login/asd
appmodule:
{ path: 'login/:token', component: AppComponent},

appcomponent.ts
ngOnInit() {

this.sub = this.route.params.subscribe(params => {
  this.usr = params['token'];
  console.log(this.usr); //THIS KEEP GETTING UNDEFINED

});
}

That usr keeps getting undefined, dont know why...
Some idea? Thanks.
I tryied things like this:
this.sub = this.route.params.subscribe(params => {
  if (!params['token']) {
    console.log('NO token'); //GOES HERE EVERYTIME
     }
  this.token = params['token'];
  console.log(this.token);
});

It gets out in 'NO token' every single time..
Something wrong with the url maybe?
Comment: Cannot match any routes when I try that.
Comment: you have private route: ActivatedRoute in the constructor right? just to make sure
Comment: Yes sir I have: private route: ActivatedRoute
Comment: Please, test this url, just to be sure: http://localhost:4200/login/40
Comment: Same result Sir. Keep getting undefined. I dont understand why.. I used params in other places and works just fine..
Comment: Can you create a StackBlitz page?
Comment: https://stackblitz.com/edit/angular-7s47c1
Comment: What are you expecting it to be? And if you look at the array in the debugger, is it just that particular key, or the whole array that is undefined?
Comment: The particular key. It supposed that if I write login/something, that key will be 'something'. But is always undefined
Answer: There is another question opened that describes your issue. This is related to ActivatedRoute state outside of arouter-outlet, in your case I believe you don't have it.
I did a test in stackbliz where you can see it working with router-outlet, but to do this I had to change the router path to another component(The AppComponent is the root component, so I did not use it).
Here is the stackblitz example:
https://stackblitz.com/edit/angular-izk361
And here much more info about this problem.
Angular 2 Activatedroute params not working in Service or outside <router-outlet>
Comment: YES SR! You were right.
For some reason the params dont work outside the router-outlet.

I move the login to other component, and get the params correctly.

Thank you!

cant get the param route angular 6


no hand joints over holographic remoting

Question: I use Holographic Remoting Player to project the unity uwp program to HoloLens. I can get the unity picture on HoloLens, move around to move the field of view, have the hand laser and air tap working well, but the hand joint visualization doesn't show up.
The player setting is ok. And I have followed the troubleshooting steps in this link, everything is ok, but the hand joint still doesn't work.
https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/Tools/HolographicRemoting.html#msbuildforunity-package-import-via-writing-into-the-packagemanifest
I have tried in Unity 2019.2.4 and 2019.4.1, both the same result. Is there anything misconfigured I need to check?
Answer: According to this document, the hand tracking profile has been updated to allow for setting the hand joint visualization to: Nothing, Everything, Editor or Player. It meaning it is possible to turn on/off hand joint visualizations while in the editor or in the device or both. So it might be a good idea to double check this field in your MRTK profile and the following way is worth trying:
Click the MixedRealityToolkit object in the Hierarchy window, and then navigate to Input->Hand Tracking in Inspector window, find HandJointVisualizationModes field and set to Everything.