Generating uniformly distributed random solutions of a linear equation

Question: Given $n+1$ variables $p_0, p_1, \ldots, p_n$ defined over $\mathbb{R}^{+}$ so that $\sum_{i=0}^np_i=1$, and given a real number $1<x<n$, I want to generate random solutions of the equation so that every solution is equiprobable (or close enough to be equiprobable) $$
0p_0 + 1p_1+\ldots+np_n=x
$$
Since all variables are real numbers, the number of solutions is infinite, but I don't know how to algorithmically choose any of them randomly in an (at least close to) uniform way
NOTE: In case it's needed, suppose I have a method $g(a, b)$ that, when called, returns a random real number between $a$ and $b$.
Possible solution: (I strongly suspect this is a solution far from being uniform). Generate $n$ random real numbers $r_i$ defined in the interval 0 to 1. They will represent coefficients of $x$ so that $ip_i=xr_i$ (since $0p_0=0$ add nothing I don't need to generate $r_0$). That means $\sum r_i$ must be equal to $1$. To make that happen, generate all the $r_i$ randomly as said, but if $\sum r_i=k\neq 1$, multiply each $r_i$ by $1/k$.
Assign $p_i=xr_i/i$ and $p_0=1-\sum_{i=1}^np_i$. For the sum of all $p_i$ to be equal to $1$ is required that $$
\frac{r_1}{1}+\frac{r_2}{2}+\ldots+\frac{r_n}{n}\leq\frac{1}{x}
$$
but I don't know if that's guaranteed or not and, even if it's guaranteed, I suspect the generated solution might not be choosen uniformely because $p_0$ is deterministically calculated.
Comment: @Eoin there's 2 equations and $n$ real variables (actually, in my case $n=7$ and $02$ there should be infinite solutions right?
Comment: [This](https://cs.stackexchange.com/questions/3227/uniform-sampling-from-a-simplex) question might get you going in a useful direction?
Comment: The notion of "uniformity" depends on the reference measure used on the resulting manifold.
Comment: You say "given $p_0,\dots,p_n$" and "given $x$", but if you are given all of those, then there is nothing to generate or sample.  I suspect you mean "given $x$, you want to sample $p_0,\dots,p_n$" from a particular distribution.  Is that correct?  If so, I encourage you to [edit] the question accordingly.
Answer: The intersection of the $n+1$ simplex
$$\{\mathbf{p}\in\mathbb R_+^{n+1};\ \mathbf{p}^\top\mathbf 1_{n+1}=1\}$$
when $\mathbf 1_{n+1}=(1,\ldots1)^\top$ and of the constrained hyperplane
$$\{\mathbf{p}\in\mathbb R_+^{n+1};\ \mathbf{p}^\top\mathbf \iota_{n+1}=x\}$$
when $\iota_{n+1}=(0,1,\ldots n)^\top$ is within a $(n−1)$-dimensional affine space
$$\{\mathbf{p}\in\mathbb R_+^{n+1};\ A\mathbf p=b\}\tag{1}$$
where $A$ is a $(2,n+1)$ matrix whose rows are orthonormal (wlog).
If $\mathbf p^0$ is a particular solution, i.e., a particular element of (1), the other members will be of the form $\mathbf p^0+\eta$ with $A\eta=0$, which can be expressed via an orthonormal basis of vectors satisfying $A\eta=0$. It is then sufficient to find an hypercube containing (1) by finding upper and lower bounds on the components of $\eta$ in (1), to generate uniformly points in that hypercube and accept simulations such that $\mathbf p^0+\eta\in\mathbb R_+^{n+1}$
Comment: As $n$ grows, this approach becomes exponentially less efficient.
Answer: Here's on possible approach, in R. It takes random samples from a simplex as starting points, and then uses optimisation to find nearby points that meet your criteria. I'm not sure how to verify that the resulting values are still "uniformly" distributed in the admissible parameter space.
<code>find_solution = function(n, x){
  # Set up our function
  basis_w = t(as.matrix(0:n))
  calculate_x = function(ps){
    xhat = basis_w %*% as.matrix(ps)
    xhat[1,1]
  }

  # Create a cost function to minimize.
  # It should penalise values of p out of the range 0-1,
  # ps that don't sum to 1, and values of x that don't match the target
  cost_func = function(ps){
    # Out of bounds loss
    too_high = ifelse(ps > 1, ps - 1, 0) %>% sq() %>% sum()
    too_low = ifelse(ps < 0,  -ps, 0) %>% sq() %>% sum()
    # Doesn't sum to 1-loss
    simplex_loss = sq(sum(ps) - 1)
    # Wrong x value loss
    xhat = calculate_x(ps)
    err_loss = sq(xhat - x)
    # Manually chosing tuning parameters
    100*too_high + 100*too_low + simplex_loss + err_loss
  }

  # Randomly sample from a simplex for starting values
  # (as array rather than matrix for compatibility with optim() )
  starting_values = hitandrun::simplex.sample(n + 1, 1)$samples %>% c()
  # Optimise
  result = optim(cost_func, par = starting_values)
  if(abs(result$value > .001)) warning('Solution not found')
  return(result$par)
}

find_solution(7, 1.5)
# [1] 0.3474378316 0.3221905230 0.0008495489 0.2713962006 0.0002233641 0.0003346271 0.0436698092 0.0138942988
find_solution(7, 1.5)
# [1] 3.889560e-01 2.736482e-01 1.178040e-01 7.962354e-02 3.027082e-05 8.923485e-02 4.931859e-02 1.381217e-03
find_solution(7, 1.5)
# [1]  2.184026e-01  3.564897e-01  2.410103e-01  1.512842e-01  9.407019e-04 -1.540388e-05  7.533937e-06  2.939822e-02
find_solution(7, 1.5)
# [1] 1.931718e-01 4.007192e-01 1.561489e-01 2.386094e-01 2.693653e-03 1.691173e-05 6.235019e-05 8.569269e-03
find_solution(7, 1.5)
# [1] 0.4523700298 0.0139939226 0.3043223032 0.1165318696 0.0502990295 0.0478577440 0.0138911475 0.0005681597
find_solution(7, 1.5)
# [1] 0.527091876 0.035665984 0.006260825 0.372083535 0.011015178 0.014363521 0.007900288 0.024702057
</code>
Comment: If indeed you are projecting to nearest solutions -- I haven't checked your code -- then your results will not have the intended uniform distribution.  The larger $n$ is, the more they will deviate from uniformity.  (This is another manifestation of the "curse of dimensionality.")


Why these two complex representations of $Cl(V)$ are not isomorphic?

Question: Let $(V,g)$ be a complex vector space of dimension $2n+1$ with symmetric bilinear form $g$. There exists a basis $a_1$, $\dots$, $a_n$, $b_1$, $\dots$, $b_n$, $c$ of $V$ such that $g(a_i,a_j) = g(b_i,b_j)=g(a_i,c)=g(b_i,c)=0$, $g(a_i,b_j)= \tfrac 1 2 \delta_{ij}$, $g(c,c)=1$ (just note that the corresponding matrix of $g$ is non-degenerate and symmetric and all such matrices are congruent to each other over $\mathbb C$).
Let $S = \wedge (a_1,\dots,a_n)$. We can define the action of $Cl(V)$ on $S$ by:
$$
  a_i(\omega) = a_i \wedge \omega, \\
  b_i(a_i) = 1, \; b_i(a_j) = 0 \; (i \neq j), \; b_i(a_s \wedge \omega) = b_i(a_s) \wedge \omega - a_s \wedge b_i(\omega), \\
  c(1) = 1, \; c(a_i) = -a_i, \; c(a_i\wedge\cdots \wedge a_k)=c(a_i)\wedge \cdots \wedge c(a_k).
$$
This defines a representation of $Cl(V)$ on $S$ which we call $S_+$. It is irreducible since for any basis elements $a_i \wedge \cdots \wedge a_k$ and $a_s \wedge \cdots \wedge a_l$ there is an element of $Cl(V)$ which sends the first one into the second one.
We can also define an irreducible representation $S_-$ of $Cl(V)$ on $S$ by defining the action of $a_i$ and $b_i$ as above and by putting
$$
  c(1)=-1, \; c(a_i)=a_i, \; c(a_i \wedge a_j) = -a_i \wedge a_j, \; \dots.
$$
It is asked in Problem 2.25 at p. 31 of these notes by P. Etingof et al. to show that $S_+$ and $S_-$ are not isomorphic. But if we compute the traces of operators $a_i$, $b_i$, $c$ in $S_+$ and in $S_-$ it turns out that they are the same so that the representations must be isomorphic. Indeed, $a_i$ and $b_i$ act in the same way in $S_+$ and $S_-$ and the trace of $c$ in $S_+$ is
$$
  1 - {n \choose 1}+ {n \choose 2} - \cdots = (1-1)^n = 0,
$$
whereas in $S_-$ it is
$$
  -1 + {n \choose 1} - {n \choose 2} + \cdots = -(1-1)^n = 0.
$$
Thus, the characters of $S_+$ and $S_-$ are the same and they must be isomorphic. Could you please point out where am I mistaken?
Answer: It is not enough to show that the characters of the $a_i$'s, the $b_i$'s and $c$ agree. The $a_i$'s, $b_i$'s and $c$ do not span $Cl(V)$ as a complex vector space.
Consider $b_n\dots b_1a_1 \dots a_n\in Cl(V)$. This is a projection onto the $1$ vector. $c$ acts on $1$ by multiplication by $+1$ if we're in $S_+$, or by multiplication by $-1$ if we're in $S_-$. So the character of $cb_n\dots b_1a_1 \dots a_n$ is $+1$ or $-1$ depending on whether we're in $S_+$, or $-1$ or $S_-$.
Comment: I think $cb_1 \dots b_n$ has character zero. But $cb_1 \dots b_n a_n \dots a_1$ should work. (see my edit of the answer)
Comment: Thank you, yes! Now I see that it is not enough to show this for characters of $a_i$, $b_i$, $c$. The trace of $c b_1 \cdots b_n$ is different in $S_+$ and $S_-$
Comment: By the way, thank you for posting this nice question. I learned a lot about Clifford algebras by working through this.
Comment: This is a nice question by P. Etingof! :)


The reason of different regression results between "enter" and "stepwise" methods

Question: I and one of my colleagues conducted regression analysis in SPSS. There is a significant difference in our regression results obtained using the "enter" and "stepwise" methods. All other settings of the two regression analyses are the same, except for the methods. There are five regressors and 19 cases.
With the "enter" method, the model is not significant (R2=.44, adjusted R2=0.16, p>0.2). But the predictor (regressor) of interest shows a significant effect on the dependent variable (p<0.05).
On the other hand, with the "stepwise" method, the model is significant (R2=.40, adjusted R2=0.36, p<0.01), and the predictor of interest also has a significant effect (p<0.01).
I would like to know why there is such a substantial difference between the two methods. Additionally, if we must use the "enter" method for regression, are there any ways to make the overall model look significant?
Comment: (1) The bootstrap does not increase the sample size.  (2) No statistical procedure alone can increase the sample size: you can't create data with mathematics.  (3) There are various rules of thumb for ordinary least squares regression, but the most optimistic say you need an average of at least 10 observations for each coefficient you are estimating.
Comment: The large difference between $R^2$ and adjusted $R^2$ indicates you have extremely few observations -- far fewer than will support estimates for five regressors.  With your 18 cases, you can *hope,* optimistically, to fit a model with at most *two* regressors.
Comment: Your edit includes a formula, and you are now trying to verify the adjusted R2. This is a different question. Briefly, your "regressors" likely include categorical variables. If a categorical variable has 10 levels, it is encoded as (and counts as) 9 separate "contrasts" or variables. So think carefully about your $k$.
Comment: I doubt that.  The bootstrap is not magical and typically it doesn't work well, or even at all, with such tiny datasets.
Comment: How many covariates are in the model with "enter"?
Comment: There are no covariates, only five regressors in both "enter" or "stepwise" regression.
Comment: Sorry, it is my fault.  All variables are not categorical variables. But the constant regressor was not included. So there are six regressors, including constant. And the adjusted R2 is different if k is six.
Comment: @whuber Thank you very much! Do you know the tools or formulas for calculating minimum sample size for regression analysis? Besides, could we use some algorithm to increase the sample size, like bootstrap?
Comment: Thanks! But bootstrap can solve the problem of decreased adjusted R2 in my regression analysis, right?
Answer: For the uninitiated, the "enter" method is language endemic to SPSS. SPSS offers stepwise as a highly suggestive "tickbox" option in any regression setting. In all other software, the "enter method" is simply regression and stepwise requires several, deliberate additional steps. The truth is that most SPSS users consider or even use stepwise regression simply because it's there. It's a major design flaw in SPSS.
In this case, you refer to the "significance" of a model. However, if stepwise regression is performed, there is no well-defined concept of a "model" - the specific hypothesis which generates a $p$-value for overall model fit sets the coefficients for all covariates in a model to 0. But when the number of covariates entered into (or removed from) said model, the alternative hypothesis has been constrained by the stepwise procedure. The final stepwise model is optimized according to that algorithm to give the best $R^2$ and the best $p-value$ for overall fit without any account whatsoever for multiple testing. In short, the $p$ from the stepwise model doesn't tell you anything useful about the global model fit.
It is surprising that the "enter" method as you call it has not achieved global model fit. The increased $R^2$ but decreased adjusted $R^2$ seems to suggest you have too many variables in the model. When there are potentially too many variables to adjust properly in a model (or in any other case as well), a trained statistician would have performed a sample size calculation via simulation or other tools to determine the optimal balance of predictiveness (via inclusion of variables) and parsimony/reduced variance inflation (via exclusion of variables).
One example when a stepwise model selection might be performed regards adjustment for precision/blocking variables in a multiple regression model. Distinct from confounding adjustment, which must satisfy causal criteria and provide bidirectional prediction (stratification more precisely) between an exposure and an outcome, precision variables are causally unrelated to the exposure, but predict/stratify the response. In this case, some of the common predictive techniques can be applied, stepwise regression included, to identify the functional form of the prediction of conditional response. However, these details are not available at present.
However, I think all SPSS users should avoid stepwise regression because it is poorly regarded in the community and introduces issues of lack of generalization. Since you have already analyzed the data, I advocate to simply report the "enter" method provided you are certain all the adjustments are valid and relevant to the science.
Comment: Thank you very much for your kind reply! Yes, the adjusted R2 is very low. But I think the number of independent variables is not the reason. Because there are only five regressors in the model.
Comment: Besides, you mentioned that results obtained through the 'enter' method can be reported directly. But if the overall model is not significant, does it still make sense for a particular independent variable to have a significant prediction on the dependent variable? The significant predictions of the regressors of interest perfectly align with our theoretical assumptions, which is crucial for us.
Comment: @AuroraChoi the "test" of "model fit" is dubious, particularly because it is not a hypothesis of interest. You can test the hypothesis as to whether a particular $\beta=0$ regardless of the overall model fit (or any hypothesis test thereof) *provided* the specific hypothesis, including the regressors *are prespecified*.
Comment: None of the SPSS procedures represent good statistical practice.


XML convert Node into String using XSLT 2.0

Question: I've searched for renaming an XML node to a string. I have found examples of strings within XML to Nodes but not the other way.
Is it possible to do the following
<par>
<run> Some text <break/> </run>
</par>

<par>
<run> some text with no carraige return</run>
</par>

To:
<par>
<run> Some text
 </run>
</par>

Many thanks in advance for any replies.
Dono
Answer: Certainly that's possible. Just use an identity transform and handle <break> specially. Instead of copying it using <xsl:copy>, output any text you like:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0">

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="break">
    <xsl:value-of select="'
'"/>
  </xsl:template>

</xsl:stylesheet>

I you want the literal output
 you can use disable-output-escaping, like
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0">

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="break">
    <xsl:value-of select="'&#10;'" disable-output-escaping="yes"/>
  </xsl:template>

</xsl:stylesheet>

However, this is an optional feature and not guaranteed to be supported by any XSLT processor.
Comment: You are a legend my friend.


Can't add local user on system using ldap auth for samba

Question: Trying to add a local user to a CentOS 6.3 system that is using ldap for Samba authentication, but being stymied by the user's existing entry in ldap.
[root@samba ~]# adduser wchandy
adduser: user 'wchandy' already exists

[root@samba ~]# useradd wchandy
useradd: user 'wchandy' already exists

User is not already a local user:
[root@edgar2 ~]# grep wchandy /etc/passwd

But they are a Samba user in ldap:
[root@edgar2 ~]# smbldap-usershow wchandy | grep uid
dn: uid=wchandy,ou=people,dc=ucsc,dc=edu
uid: wchandy
uidNumber: 30490

adduser does not have a local option. How does one get adduser to work properly to add local users in the presence of ldap authentication.
Other things to consider:

There are currently local users who share a uid with an ldap entry
(with a different uidNumber) who can access samba and ssh
independently.
No, I don't want to edit the user directly into /etc/passwd and /etc/group.
I'd like to fix the underlying problem. Plus the local entry interferes with access to samba.
No, I don't want to rely on ldap for local ssh login.
No, I don't want to use a different uid for the user.

I originally set up my samba-ldap authentication with the handy (but seemly irreversible) authconfig command:
[root@samba ~]# authconfig --enableshadow --enablemd5 --enableldap \
--enableldapauth --enableldaptls --enablemkhomedir \
--ldapserver=dir.mydomain.com --ldapbasedn="dc=mydomain,dc=com" \
--enablelocauthorize --updateall

My /etc/sysconfig/authconfig looks like this:
IPADOMAINJOINED=no
USEMKHOMEDIR=yes
USEPAMACCESS=no
CACHECREDENTIALS=yes
USESSSDAUTH=no
USESHADOW=yes
USEWINBIND=no
PASSWDALGORITHM=sha512
FORCELEGACY=no
USEFPRINTD=yes
USEHESIOD=no
FORCESMARTCARD=no
USEDB=no
USELDAPAUTH=yes
IPAV2NONTP=no
USELDAP=yes
USECRACKLIB=yes
USEIPAV2=no
USEWINBINDAUTH=no
USESMARTCARD=no
USELOCAUTHORIZE=yes
USENIS=no
USEKERBEROS=no
USESYSNETAUTH=no
USESSSD=no
USEPASSWDQC=no

My samba config was migrated from an RHEL4.x system to CentOS 6.3.  Now instead of the kludgy mashup of nss and pam and who knows what, CentOS 6.x uses the pretty slick and easy sssd.
My /etc/sssd/sssd.conf looks like this:
[domain/default]

cache_credentials = True
#cache_credentials = False
ldap_search_base = dc=mydomain,dc=com
krb5_realm = EXAMPLE.COM
krb5_server = kerberos.example.com
id_provider = ldap
auth_provider = ldap
chpass_provider = ldap
ldap_uri = ldap://dir.mydomain.com/
ldap_tls_cacertdir = /etc/openldap/cacerts
#ldap_tls_reqcert = allow

entry_cache_timeout = 5

debug_level = 31

[sssd]
config_file_version = 2
services = nss, pam
# SSSD will not start if you do not configure any domains.
# Add new domain configurations as [domain/<NAME>] sections, and
# then add the list of domains (in the order you want them to be
# queried) to the "domains" attribute below and uncomment it.
# domains = LDAP
domains = default

#debug_level = 31

[nss]

[pam]

debug_level = 31

Thanks for the help. If I can get my local and samba-ldap authentication working independently I'll be stoked.
UPDATE: While there are some reasonably sufficient workarounds below, here's a parapharse of the advice I got from the experts at the sssd_users list: "Yes, it may have worked in earlier OS versions using nss and pam, it wasn't the best practice to allow shared UIDs. Newer systems using sssd prevent this." While my use case was perfectly valid, my system prevented what I wanted to do by intention.
However, I never did find a way to unset or reverse any of the many changes that authconfig wrought to my system. So if the parameters I gave to authconfig were wrong, there was no going back.
Comment: Keep in mind that sssd is *consumed* by NSS and PAM; it does not replace them. You still need to understand those services and how they interact with it.
Comment: I am definitely not an NSS, PAM, or sssd expert, I feel like I should still be able to effectively configure it.  No answer to this question has yet been offered.
Comment: This does not answer the original inquiry, but I had to find some temporary workaround: I created a local user with a different UID to give ssh access to a person who already had an LDAP/Samba entry.  Possibly the cheeziest sysadmin solution I've done in years.
Comment: Okay another workaround, still less than optimal:  Adding the local user with the same uidNumber as the LDAP entry.  That allows both local and Samba access.
Comment: Fixing the underlying problem unfortunately means working with the software authors or submitting a patch yourself. We cannot help you do something that the command simply does not support.
Comment: Additionally, your edit now adds conflicting logic: you want the useradd command to work despite the duplicate username, but adding local entries manually interferes with samba? Please edit your question to focus on the *specific* problem you want solved.
Comment: Andrew, I appreciate your taking the time to respond, and I don't think the request is unreasonable nor confusing. To be concise:  **I want to know how to configure sssd, nss, and pam (preferably with the authconfig tool) to allow local authentication exclusively from /etc/passwd while allowing Samba to use LDAP exclusively for authentication.** In fact, I had a RHEL4 system configured precisely this way.
Comment: And I strongly believe this is a configuration issue, a gap in my understanding of the complex systems involved, not a software engineering issue. The authors would no doubt have an answer to my query, and perhaps that is where I should seek.  There is a mailing list for sssd users.
Comment: At least for me, the presentation wasn't very clear. Between the subject and *How does one get adduser to work properly to add local users in the presence of ldap authentication.*, your intent shifts more toward "how do I get useradd to let me do this" than "how do I dis-entangle these two services". If you edit the question to focus on your actual intent from the beginning, it'll probably pass the re-open queue and we'll take another shot at it.
Comment: No I don't think this question was unclear. I edited the title to better reflect the problem.
Comment: Looking at things again I think I have a better idea of what you're looking for; I just think we were just talking around each other in circles. Drop by [this SF chat](http://chat.stackexchange.com/rooms/info/13405/discussion-between-andrew-b-and-wes-modes) if you still need help and we'll work it out without spamming this question.
Comment: Thanks, Andrew. The workarounds were sufficient. It's been a while, but I believe the answer I finally got from the sssd_users list is: "Yes, it may have worked in earlier versions, but it wasn't the best practice to allow shared uids. Newer versions prevent this." While my use case was perfectly valid, sssd (which replaced some of the other systems cobbled together with dental floss and chewing gum) doesn't allow it." In fact, I should add this to the original question.  Thanks!
Comment: If you need to untie `passwd` lookups from sssd, remove sssd from the corresponding entry in `/etc/nsswitch.conf` (unless there's a daemon that breaks by doing this). You really can't get away from understanding NSS and PAM when doing elaborate overlays. sssd is implemented by modules for both, and is not a replacement.
Answer: My last answer was bad, ignore that.
I believe your only option is manual editing of /etc/passwd (vipw is preferred because it saves you from your own mistakes). The -o option allows you to create multiple names for one UID, but there isn't an equivalent option for telling passwd to ignore the name already existing when it performs a NSS lookup.
getent passwd will show you how the uids cascade once you've added the user; the first entry wins. Make sure the uid is identical to avoid issues with shifting permissions. (your examples did not include -u syntax)
Comment: Please see above:  "No, I don't want to edit the user directly into /etc/passwd and /etc/group. I'd like to fix the underlying problem. PLUS THE LOCAL ENTRY INTERFERES WITH ACCESS TO SAMBA."  So, unfortunately, no, that isn't a solution.
Answer: Neither of these two workarounds are optimum, but they do give sysadmins a way of moving forward if they find themselves in the sticky situation where LDAP and the local passwd file are blocking each other.
Workaround 1: I created a local user with a different UID (username) to give ssh access to a person who already had an LDAP/Samba entry. Possibly the cheeziest sysadmin solution I've done in years.
Workaround 2: A little more complicated but comes down to adding the local user with the same uidNumber as in LDAP.

Lookup LDAP uidNumber with getent, ldapsearch, or smbldap-usershow
Temporarily disable the user in LDAP in order to add the local user
without conflicts
Create the local account matching the uidNumber with LDAP
Re-enable the user in LDAP

Both of these work, but neither address the underlying issue of allowing the authentication to use LDAP exclusively for Samba auth and /etc/passwd for local auth.  But in the absence of another solution, this will have to do.


Persisting an Entity in derby DB Using EntityManager gives java.sql.SQLIntegrityConstraintViolationException

Question: I am getting the following Error when i try to persist an Object using Entitymanger in Derby DB:-
<code> Internal Exception: java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL150318192139760' defined on 'TESTSEARCHS '.
    Error Code: 20000
    Call: INSERT INTO TESTSEARCHS (SEARCHID) VALUES (?)
        bind => [1 parameter bound]
    Query: InsertObjectQuery(example.com.TestSearchs@4e049f)
</code>
The associated code is :-
<code>  public class TestA extends SuperA{
            @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
            protected TestSearchs testSearchs;
    ........
        }
</code>
The SuperA class provides the ID for TestA
<code>  @Entity
  @XmlTransient
  @MappedSuperclass
  @Inheritance(strategy = InheritanceType.JOINED)
  public class SuperA{
      @Id
      private String id;
    .........

    }
</code>
and the TestSearchs class is :-
<code>public class TestSearchs {

    @Id
    @GeneratedValue
    @XmlTransient
    private long searchId;

    @ElementCollection(targetClass = String.class,fetch = FetchType.EAGER)
    protected List<String> testsearch=new ArrayList<String>();

.....

}
</code>
I set the Id by calling setter of TestA which is Unique,And then i persit the TestA object using entityManager.Persit() but the following error occurs.Please Tell me what m i doing wrong?
Answer: Does this help (on TestSearchs)?
<code>@GeneratedValue(strategy = GenerationType.TABLE)
</code>


Dealing with pdf files

Question: I am implementing an application which its main idea is reading books using it.
the pdf files are on my server and I want the user to read the book without saving it on their device.
I thought about streaming the pdf file or embedding it. but it has some difficulties.
So, what is the best solution for this issue?
I am using Django-Rest-framework and Flutter
Comment: If you  are consuming the api, just display the file endpoint, however, if you are building the endpoint add a FileField(), configure django to receive file archives with Pillow and display the archives path/url into your endpoint.
Answer: i think you have to use list of this packages for reading pdf files into flutter.
https://pub.dev/packages/syncfusion_flutter_pdf
https://pub.dev/packages/syncfusion_flutter_pdfviewer
Comment: are these packages don't require saving the pdf file in the user device?
Comment: yes bro just give your pdf links to it and enjoy it's fetures

Dealing with pdf files


Rule to create a Node from a Webform Submission

Question: Using Rules with Webform Rules enabled, how would I make a new node after a webform submission and use the submitted values as field values in the node?
In short, how do I turn webform submissions into nodes using Rules.
I've set up the Rule like this:

Where do I go from here? I can't seem to find a way to move webform submission values into the node's fields.

Please note: I have read "Using webform rules to create node after webform submission" and "How to create a node with submissions of a webform?". Unfortunately, neither address my question.
Comment: The whole point of http://drupal.stackexchange.com/questions/80022/how-to-create-a-node-with-submissions-of-a-webform is that you do not need to take the extra step via Rules and Webforms. Create the nodes directly.
Comment: @Jeroen Thank. But is it possible to do it the way I've outlined?
Comment: Have a look at [this question](http://drupal.stackexchange.com/q/199821/39516), and my answer to it. Not sure if your question is a duplicate of that question, but possibly my answer to that question also works for your question, no?
Comment: @Jeroen, it's often necessary to provide a more user friendly version of a form. I tend to use a mix of node/add and entity forms.
Comment: @Pierre.Vriens, this is the right answer. I'd add that sometimes it is necessary to force save a node after creating it in the rule for some entity reference (OG mainly) things to work.
Comment: And finally, when it's very complicated and standard rules won't work, you can use https://www.drupal.org/project/rules_session_vars to add values to $_SESSIONs and create a second rule for when a node is created. You add conditions for the Sessions and then delete them at the end of the rule. I've had to do this only twice.
Comment: hey @NiallMurphy ... which answer do you mean by that "this is the right answer"? Also, didn't know about that session vars module, merci for the hint! I'm trying to picture appropriate use-cases for it. Think of something like some Rules scenario related to anonymous users (where you can't use a custom user field since user is not logged in). would that be a good case to use this interesting module? Otherwise, why not post a sef answered question containing an appropriate case?
Comment: I mean your link to your answer about "entity has field". I actually have a broken collarbone and can only type extremely slowly with my bad hand so I'm avoiding full answers or extra typing :p There are many uses of the module that can create very interesting add-on rules that would otherwise be impossible.
Answer: Below is something I learned about using webform data in Rules, which may help you to get this to work ... (assuming this question is about D7).
You have access to all labels and all values of any field of a webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

So try to use similar tokens.
For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform).
the 2nd attempt explains what to do in case of Webform.

Note: if your target field is a multi value field, using "Set a data value" is completely wrong. Instead you need to use an action like "Add item to a list". Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for way more details about "Add item to a list".
Comment: Yeah, I think this is the missing piece. Thanks. Seems like a good place to start, anyway. What if the destination field on the node is a select list?
Comment: Thank you for the feedback (and accept). Not sure how to correctly understand your question in your last comment. Actually what's the problem, or what's stopping you from getting that to work? Maybe it's worth posting a new question?
Comment: This works when the destination field in the node is a text field. I have one that's a select list. The source is an identical select list in the webform, but I can't get the webform selection value populate the node's select value.


Insert squares into square

Question: Let $ABCD$ be a square, $AB=2a$
Is it possible to insert two disjoint squares, both of side $a$ into $ABCD$?
Comment: I think if we prove that any a-sided square will contain the centre point of ABCD, that will be enough.
(Somebody said that, but later he just deleted his post)
Comment: Can the squares touch in the corners?
Comment: No, they can't....
Answer: Let $\mathcal C$ be the circle with radius $a$ inscribed in the square $\mathcal A$ of side $2a$ centered, say, at point $O= (1,1)$ and consider the distance $d = d(\mathcal C,\mathcal S)$ where $\mathcal S$ is any square inserted in $\mathcal A$; if $\mathcal S \cap \mathcal C$ is not empty  then $d = 0$, which is obvious. On the other hand the biggest square $\mathcal S$ contained in $\mathcal A$ and out of $\mathcal C$ --and having a point in common with $\mathcal C$, so $d = 0$ again-- has its diagonal equal to $(\sqrt2-1)a$ (there are four, each placed in one corner of $\mathcal A$) then its length $l=\frac{\sqrt2-1}{2}a<a$ . Consequently, if $\mathcal S$ and $\mathcal C$ are disjoint forcibly $l<a$. Therefore the answer to the problem is negative.
Comment: I don't understand how this solves the problem. Just because two squares touch the circle doesn't mean they're touching each other. Am I missing something here?
Comment: Who is B, please?
Comment: Hi Robert. I have edited the errors  (not only of the lapsus with B but true mistakes conditionated by the rush. My english is weak, apologize me please)
Comment: No time now, but I trust you and I think I must have mistaken
Comment: Yes, I had an error by omission; sorry, excuse me please.
Answer: Suppose the big square with side length $2$ is $ABCD$ (starting from $A$ in the lower left corner and going clockwise.) And the small square with side length $1$ is $EFGH$. I'll prove that $EFGH$ must contain $I$ (the center of $ABCD$) Somebody else came up with the idea, but I don't remember his name so I can't give credit.
I'll assume that $E\in[AD]$ and that $F\in[AB]$, i.e. two corners of $EFGH$ are in contact with $ABCD$. We can use this to prove it for the general case. But I don't feel motivated enough to think about it. I believe we can do it just by translation of $EFGH$ until it is in contact with two sides.
We'll use Cartesian coordinates for our squares. So we have:
$A(0,0),\ B(0,2),\ C(2,2),\ D(2,0)$ and $E(x,0),\ F(0,y)$
$s.t.\ 0\leq x,y\leq 1 $ and $ x^2+y^2=1$
We need to determine the coordinates for $G$ and $H$.
You can get $G$ by rotating $E$ around $F$ by $\displaystyle\frac\pi2$.
$$(x_G-0,y_G-y)=rot_{\pi/2}(x,-y)=(y,x)$$
$$x_G=y\ ;\ y_G=y+x $$
Now similarly for $H$, you get:
$$x_H= y+x\ ;\ y_h=x$$
Now we need to show that $I(1,1)$ is in our rectangle.
We'll show that $I$ is: a) under $(FG)$, b) above $(EH)$, c) to the left of $(GH)$ and d) to the right of $(EF)$. I'll only prove the first two, since you can use the same method for the others.
a)
The equation for $(FG)$ is: $Y=y+\frac{x}{y}X$
$$1\leq y+\frac xy\cdot1 = \frac{x+y^2}{y}=\frac{x+1-x^2}{y}=1+\frac{1-y}{y}+\frac{x(1-x)}{y}$$
So $I$ is under $(FG)$:
b) The equation for $(EH)$ is: $Y=\frac{x}{y}(X-x)$
$$1 \geq \frac{x}{y}(1-x)=\frac{x}{y(1+x)}(1-x^2)=\frac{xy}{1+x}$$
So $I$ is above $(EH)$
c) and d) are true because of symmetry. So $I$ is inside $EFGH$
If two squares of side length $1$ are inside $ABCD$ they both contain $I$, so they can't be disjoint.
Comment: Im not sure the equation for (FG) is: Y=y+x/yX. In my opinion, the correct equation is (FG): Y=-y+x/yX
Comment: @Robert If you plug in $X=0$, you should get $Y=y$, not $Y=-y$.
Comment: You are right. That was my mistake.
Anyway, I don't understand why y+x/y=(x2+y2)y
Comment: @Robert Oh, that was a mistake. I'll see if I can fix it.
Comment: @Robert I think it's correct, now.
Comment: I seems to be OK now. Thanks!

Insert squares into square


How to solve homogenous ODE with zero as initial time $t_0$

Question: I'm trying to solve the ODE
$$y' = \frac{t + 2y}{2t + y}$$
as general homogenous equation. Thus I'm using general initial conditions $y(t_0) = y_0$ with the only restriction $2t_0 + y_0 \neq 0$ (otherwise the denominator would be zero in the defining equation). Notice, that this condition doesn't imply $t_0 \neq 0$.
At this point I want to solve ODE using a transformation into a homogenous equation. Thus look at it like this
$$y' = \frac{1 + 2\frac{y}{t}}{2 + \frac{y}{t}}$$
Expanding with $t$ in the nominator and denominator shows that the equations are equivalent. Then substituting $z = \frac{y}{t}$ yields the separable equation
$$z' = \frac{1}{t} (\frac{1 + 2z}{2 + z} - z)$$
Now I'm wondering about what happens if the initial value $t_0$ was zero. In this case the substitution doesn't work. What am I missing here?
Comment: What if you let $y = tv$, then $y' = v + t v'$? Substitute and that likely helps.
Answer: $$y' = \frac{t + 2y}{2t + y}$$
There are many ways to integrate this Differential Equation, @Moo's trick is one of them. Here is another way:
$$\frac {dy}{(t + 2y)}=\frac  {dt}{(2t + y)}$$
$$\frac {d(t+y)}{3(t + y)}=\frac  {d(t-y)}{(t - y)}$$
Integrate:
$$\ln \left | \dfrac {t+y}{(t-y)^3}  \right|=k \implies \left | \dfrac {t+y}{(t-y)^3}  \right|=c$$


Subtracting minimums bound

Question: Consider $|\min f-\min g|$. Can we bound this in terms of $\min f-g$ or $\min |f-g|$?
I know that $\min f+\min g\leq \min f+g$ and I know that $\min g=-\max (-g)$ but I'm not sure how to proceed.
Answer: Generally, no.  Let $f=(0,0,1000,0,0), g=(0,1000,0,0,0)$.  Then $|\min f - \min g|=0$ but $\min (f-g) = -1000$ and $|\min (f-g)|=1000$.  This should help you think about examples for bounds that somebody might suggest.
Comment: But that $1000$ is not expressed anywhere in the minima of $f$ and $g$.

Subtracting minimums bound


loadNibNamed() fails: Unknown class  in Interface Builder file

Question: I've moved code to an Xcode framework and now a loadNibNamed() fails with (I changed the readable parts of the mangled Swift identifier name):
Unknown class _TtC13MyFramework14MyTableCell in Interface Builder file.

The loadNibNamed() is called from a Swift file that has MyFramework Target Membership.
The UITableViewCell subclass (MyTableCell) is an Obj-C class. It's header has public MyFramework Target Membership, and its .m is also member of the framework.  The cell is very simple, having an UIImageView and a few UILabels, no custom classes.
In the XIB the table cell's Class has been set to MyTableCell.  And, Module to MyFramework, with Inherit Module From Target selected.
I've set the Product Bundle Identifier of the framework.  And I get the bundle using:
[NSBundle bundleWithIdentifier:@"com.mycompany.myframework"];

The bundle is found; checked by printing its bundlePath.
I've looked up this issue and have tried all kinds of variations, for example not assigning ``MyTableCell`'s Module, but nothing works.  I've also created a new cell XIB with a Swift class, but with the same result.
Any ideas what I should/could still try?
Comment: I've mostly encountered this `this class is not key value coding-compliant for the key myImage` error when deleting the IBOutlet from source file and that was still connected to storyboard. So maybe, you have Outlet connection in storyboard with name `myImage`. Please check if it helps
Comment: The `class is not key value coding-compliant` is a side-effect of my subclass not being found. That's not the first/main issue.
Comment: Have you tried creating an instance of `MyTableCell` programmatically to see if there are any more useful error messages?
Comment: @waldrumpus `let cell = MyTableCell()` simply works; just tried it to double check.
Answer: I figured out some solution that works for me - YMMV.
So in my situation I needed to expose some custom Swift UIControl subclasses to the Objective C runtime. I did this by adding an annotation as such:
@objc(CustomButton)
public class CustomButton: UIButton {
    // some implementation
}

When this class was added to a Framework an error appeared, quite similar as yours.
Unknown class _TtC9CustomFramework12CustomButton in Interface Builder file.

To fix this issue I had to modify my XIB file to remove the module.

When adding the framework to another project all works fine now. No errors and the custom views appear as expected.


what does a high optimal shrinkage value indicate?

Question: My optimal shrinkage value is high after comparing the MSE for different combinations of parameters. I'm wondering what does it mean to the data structure or signal structure? Can I say this dataset has many relevant predictors?
Comment: What exactly do you mean by "optimal shrinkage value"?
Comment: You can't interpret "the shrinkage value" on its own. You need to see it in comparison to your regression parameters. And you need to explain what shrinkage you are using in the first place (Lasso, Ridge, Elastic Net, ...). And even then, there is likely no simple answer.
Comment: The shrinkage value I used to fit the best model(lowest MSE)
Comment: @StephanKolassa Well, that depends. For example, if shrinkage is zero, then ridge becomes OLS. Now if one scales the shrinkage (ridge does that but Tikhonov would not) then greater shrinkage means more injected bias.
Answer: The shrinkage rate value $\eta$ (aka. learning rate) in the context gradient boosting does not mean anything particular individually. It helps us control the rate over which our prediction function is adapting its shape.
$\eta$ is vaguely related to the size of the dataset. Everything else being equal, a larger dataset should require a "higher" $\eta$ to converge to a stable shape than a smaller dataset; with the larger dataset we would not need to explore our function space as diligently. The shrinkage rate by itself though does not relate to the signal structure or indicates if our dataset contains relevant predictive features.


How to send keys to a Half Life 1 window?

Question: I am trying to send the "Up arrow" to a Half Life 1 window using the following code:
<code>#include <Windows.h>

int main()
{
    Sleep(3000);

    // Up arrow
    keybd_event(VK_UP, 0, 0, 0);
    keybd_event(VK_UP, 0, KEYEVENTF_KEYUP, 0);

    return 0;
}
</code>
But it is not working! does Half Life 1 only allows somehow the key presses to be sent from the actual hardware keyboard?
Comment: @user it's normal for games to behave this way. You probably need to work out how this program accepts input.
Comment: @BeyelerStudios But not only to that? I think the cause may be `keybd_event` isn't sending scancode here. `SendInput` may be useful.
Comment: Did you try whether other applications, e.g. Notepad receive keyboard events this way?
Comment: @Serge Rogatch Yes it works with Notepad and other applications.
Answer: The thing is the game will receive your inputs but it doesn't handle the events because it has no instructions to handle the event. I mean it will have keyboard event handling code but they will obviously override your actions.
Comment: I think this was meant to be a comment.


Apache 2 with Weblogic Plug-in Redirection, original location still requested to backend

Question: We're trying to setup an SSL server in front of a Weblogic server using Apache as the SSL provider. Here's what's inside of our httpd.conf:
<code><Location /original>
     SetHandler weblogic-handler
     WebLogicHost 10.11.1.1
     WebLogicPort 8700
     PathTrim /original
     PathPrepend /destination
     ConnectTimeoutSecs 60
</Location>

<Location /destination>
     SetHandler weblogic-handler
     WebLogicHost 10.11.1.1
     WebLogicPort 8700
     ConnectTimeoutSecs 60
</Location>
</code>
This setup works mostly, but in the ssl_error_log file there're these entries:
<code>[Wed Aug 11 14:59:00 2010] [error] [client xxx.xxx.xxx.xxx] ap_proxy: trying GET /original at backend host '10.11.1.1/8700; got
     exception 'CONNECTION_REFUSED [os error=0, line 1739 of ../nsapi/URL.cpp]: Error connecting to host 10.11.1.1:8700'
</code>
The weird thing is, the redirection still works, but these annoying entries still shows up. Anyone can point out where did we go wrong? Thanks.
Answer: You might want to tune weblogic with Accept Backlog
To tune the Accept Backlog value from the Administration Console:

Start the Administration Server if it is not already running.
Access the Administration Console for the domain.
Expand the Servers node in the left pane to display the servers configured
in your domain.
Click the name of the server instance that you want to configure.
Select the Configuration -> Tuning tab.
Modify the default Accept Backlog value as necessary to tune how many TCP  connections can be buffered in a wait queue:During operations, if many connections are dropped
or refused at the client, and no other error messages are on the server, the Accept Backlog value might be set too low.

If you are getting "connection refused" messages when you try to access  WebLogic Server, raise the Accept Backlog value from the default by 25 percent.
Continue increasing the value by 25 percent until the messages cease to appear.
Click Apply to save your changes.
Answer: You are seeing original path only because the backend wasnt available, check it in your weblogic access logs.
If your connections to weblogic are being backlogged you should see very high thread usage and this is what you have to solve, identifying the resource causing contention and either using less of this resource or increasing its availability.


Android empty ArrayList and Spinner

Question: Hey i'm creating Android application which connect with my database MySQL. I created an ArrayList with categories and added it to Adapter and then to Spinner. I see Spinner items but after onClick nothing happens and when I try to check what is in my ArrayList I see that it is empty.Data downloaded.
After click in Spinner nothing change

Here is my code:
public class InsertProductActivity extends AppCompatActivity {
    Spinner categories;
    String categoriesURL = "myURL";
    ArrayList<String> downloadedCategories = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert_product);
        categories = findViewById(R.id.categories);
        getCategories();
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        categories.setAdapter(adapter);
    }
    protected void getCategories(){
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL
                , new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("categories");
                            for(int i=0;i<jsonArray.length();i++){
                                downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
        });
        requestQueue.add(jsonObjectRequest);
    }
}

Answer: try this one.
protected void getCategories(){
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray jsonArray = response.getJSONArray("categories");
                downloadedCategories = new ArrayList<>(); // try to add your instantiation of your arrayList here.
                for(int i=0;i<jsonArray.length();i++) {
                    downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {

    }
});
//this block of code will prompt after your downloadedCategories finish storing your objects to your arrayList because if you put this in onCreate this wil call before your getCategories process not finish yet. So much better its much safer here.
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    categories.setAdapter(adapter);
    requestQueue.add(jsonObjectRequest);
}

Comment: In your solution when I try add downloadCategories to adapetr it is empty, i added initializing after for loop in try block and now it is working :)
Comment: well that's nice :) i added my instantiation before `for loop` if this helps you. You can mark this as an answer thank you :)

Android empty ArrayList and Spinner


Install APC/eaccelerator and Memcached php-extensions on shared hosting

Question: let's say I want to improve my application's performances.And I want to use an Opcode cache tool such as APC or eaccelerator and apply variable caching using Memcached.
Let's say then I'm a beginner and I have built a working-app using the above specifications.
When I need to publish my site (remote) and I'm looking around for the best "hosting solution" which host-parameters should I care about when it comes to install php extensions such those for my caching tools?Is it even possible to do that using a shared host?
I'm working on a windows environment but I read that Installing such caching tools (or whatever) on Linux server I need to type few commands within a shell..Do this mean host should provide me with a shell window?I'm very confused about this topic.
Hope you can help me out
thanks
Luca
Answer: Shared hosting providers are basic, very basic, and unless you're very lucky to get an outstanding one it's unlikely they'll install any custom software beyond a basic LAMP stack. And no shared hosting provider will give you a shell with permissions to install software (Known as 'root').
Sounds like your app would be much better suited to a decent VPS (Virtual Private Server) provider. VPS basically gives you all the features you would expect from a full dedicated server* but it's cheaper because the host will run multiple 'virtualized' servers on the same physical box.
If you're not that familiar with Linux I'd advise you go for a managed solution. I'd suggest LiquidWeb as their support service will fit your requirements perfectly. They look after everything, if your server goes down at 2AM they fix it and if you need any software installed just ask them and they'll do it. They even have a "best effort" policy on software installs so even if it's software they've never used before their support guys will spend up to 45 mins trying to install it. But even better, they'll give your root access so you can go in yourself and get a terminal to install software and play with settings safe in the knowledge that if you screw stuff up they can come in and fix it =)
In the interest of fairness, there are many good VPS providers around; SliceHost, Dataflame, and about 100 others but I've only had experience with LiquidWeb.


How to hide few product page until the User Login in Woocommerce?

Question: I want to hide few products from Unregistered/non-login users. I have the following code. The code hide the whole category, but I want to hide a few products. If a user has the link to the product and tries to open a page, an error message should display.
function my_product_query( $q ) {

    // Not logged in
    if ( !$is_logged_in ) {
        $q->set( 'tax_query',
            array(
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'slug',
                    'terms' => $cat, // your category slug
                    'operator' => 'NOT IN'
                )
            )
        );
    }
}
add_action( 'woocommerce_product_query', 'my_product_query', 10, 1 );

Answer: First of all, you can add the custom field to all the products to find out whether the product is for logged-in users or non-logged-in users. Then, you can use below code for redirect non logged-in users.
add_action('template_redirect','custom_single_product_redirect');
function custom_single_product_redirect(){
    if (class_exists('WooCommerce')){
        if(is_product()){
            $is_loggedin = get_post_meta(get_the_ID(), 'your_meta_field_key'); //get product meta key value, assuming boolean
            if($is_loggedin == 1 && !is_user_logged_in()){ //if user is not logged in and meta key is set to only for logged in users
                wp_redirect(home_url('/shop/'));
                exit();
            }

        }
    }
    return;
}

Comment: What shall be changed in the code. I want to display only visible category to logout users, and login users can see each and every category.
Comment: The above will restrict user to access particular product. If you want, you can use the same custom field to Category and same condition for the category page.
Comment: I pasted the same code (did not make any changes in code), but the code is not working. Login and logout users can access the shop, category & product page.
Comment: The above is only for the product detail page. Also, have you added the meta field for the product (to check if the product is for logged-in users or non-logged in users)?
Comment: meta field for the product? Do you mean custom fields on the product page?
Comment: Yes, custom field on the product which will help to find whether product is available for logged in users or not.


Validity of an argument

Question: Can anyone help me solve this question?
Determine whether the following argument is valid. Explain why:
"If Batman were able and willing to prevent corruption, then he would do so. If Batman were unable to prevent
corruption, he would be ineffective; if he were unwilling to prevent corruption, then he would be cruel. Batman
does not prevent corruption. If Batman exists, he is neither ineffective nor cruel. Therefore, Batman does not
exist."
Comment: I thought the usual argument made by people who believe in Batman was that Batman could prevent corruption, but he doesn't because he wants to give us the freedom to act on our own volition, and this isn't cruel because free will is more important than freedom from corruption.
Comment: @MJD I suggest such people who believe in Batman study The Batman of Spinoza.  More seriously, if memory serves me correctly this sounds to me more like Epicurus or one of Hume's characters talking about "Batman" where "Batman" is a code word for "Spiderman"... obviously.
Answer: What do you know that you can bring to bear on this question???
It could be that you are being asked to informally assess the argument (in something of the manner suggested in @Lord_Farin's answer). But (since you are asking in a maths forum!), here's how I imagine you are intended to tackle the question:

The inference here turns on the propositional connectives "if ..then ...", "and", "not" and "or" -- so obvious first step: render the argument into the language of the propositional calculus.

Do you know how to do that?

Second step: use the truth-table test to determine whether the formalized argument is valid.

Do you know how to do that?
If you in principle know how to do both steps, this example is straightforward  and should present no problems (this site isn't for doing all your homework for you! -- but ask again if you got stuck at a particular stage)  If you don't know how to do both steps then you'd better do some background reading and get up to speed!
Answer: This argument reminds me of some "proofs" of the non-existence of god. First, you assume that god is good and omnipotent and then notice that despite god being all that there is still evil in the world. Ergo, god doesn´t exist.
The argument is valid, and to see that all you need to know is that P => Q is equivalent to not Q => not P. And that if any proposition is implying a contradiction, then that proposition must be false.
Batman exist. => Batman is not cruel. Batman exists also implies that Batman is not ineffective. Bataman is neither ineffective nor cruel => he prevents corruption. And so Batman exists implies both corruption is prevented AND corruption is not prevented. Therefore that statement must be false.
Comment: "P => Q is equivalent to not P => not Q" No it most certainly isn't!!!
Answer: Let us recall the definition of valid argument:

An argument is valid iff the truth of all its premises implies the truth of its conclusion.

So let us assume that the following are true:

If Batman were able and willing to prevent corruption, then he would do so.
If Batman were unable to prevent corruption, he would be ineffective.
If Batman were unwilling to prevent corruption, then he would be cruel.
Batman does not prevent corruption.
If Batman exists, he is neither ineffective nor cruel.

The key argument that we will need is the equivalence of an implication with its contrapositive. That is:

$p \implies q$ is equivalent to $\neg q \implies \neg p$

In words:

If $p$ implies $q$, and $q$ is false, then $p$ is also false. Moreover, if the falsehood of $q$ implies the falsehood of $p$, then the truth of $p$ implies the truth of $q$.

We obtain the following contrapositives:

If Batman would not prevent corruption, he would be either unwilling or unable to do so.
If Batman would not be ineffective, he would be able to prevent corruption.
If Batman would not be cruel, he would be willing to prevent corruption.
N/A
If Batman is not neither ineffective nor cruel (i.e., if Batman is ineffective or cruel), he does not exist.

So let us get started with these nine statements.
We see that it suffices to verify the antecedent of 5. from the second list: that Batman is ineffective or cruel.
By 2. and 3. of the first list, it is sufficient that Batman be unable or unwilling to prevent corruption.
By 1. of the second list, it is sufficient that Batman not prevent corruption.
This is precisely the statement of 4.
We conclude that the truth of the premises implies the truth of the conclusion.
That is, the argument is valid.

As a side remark, I think it is sad that mathematical writers consider it necessary or pleasing to let their view on religion (a distinctly non-scientific thing) permeate into their work, thinly veiled or not. Just sad. You'd expect them to know better.

Validity of an argument


How can you visualize Independence with Venn Diagrams?

Question:
Imagine two events $A$ and $B$ that are not mutually exclusive, such that $P(A) = 0.3$ and $P(B)=0.4.$ Consider the Venn diagram of the two overlapping sets, and visualize moving them closer together or further apart, thus varying the size of the overlapping region $A \cap B$. It should be $\color{darkorange}{\text{clear}}$ that $P(A \cap B)$ could take on any value between $0$ and $0.3$, but of that infinite set of possible values, the only one that would make $A$ and $B$ independent would be $P(A \cap B) = 0.12.$

After reading this answer (excerpted above), I drew Venn diagrams below for $P(A \cap B) =0$ (when $A$ and $B$ are disjoint), $P(A \cap B) =0.12,$ and for $P(A \cap B) =0.3$ (when $B \subsetneq A)$.
However, it is $\color{darkorange}{\text{not
clear}}$ to me that the only one that would make $A$ and $B$ independent would be $P(A \cap B) = 0.12$. I still can't intuit or visualize independence.
Comment: Essentially, you want $B$ to be proportionally as big in $U$ as $A\cap B$ is in $A$. In other words, since $40$ percent of $U$ belong to $B$, you also want $40$ percent of $A$ to belong to $B$.
Answer: It's not feasible to represent independence. Most people think drawing Venn Diagrams that are disjoint demonstrates independence, but that is false. If two events are disjoint, they are inherently dependent. Because if I know A occurs, I know B cannot occur and vice versa.
So what about the opposite: drawing Venn Diagrams that intersect? This method isn't quite useful for visualizing independence either. For example, let A be the event Susan studies for her test and let B be the event Susan eats chocolate. The intersection in the Venn Diagram means that Susan studies for her test and she eats chocolate. Let's say these two events are independent. That doesn't mean these two events can't co-occur, i.e. intersect. They can. Likewise, let's say the events are dependent. They can still co-occur or not co-occur. So there, we have shown that we can't demonstrate independence via intersection either.
Answer:
In the above universe, $a,b,c$ and $d$ denote probabilities. \begin{align}&\text{events }X \text{ and } Y \text{ are }\textbf{independent}
\\\iff &P(X\cap Y)=P(X)P(Y)
\\\iff &\frac{c}{a+b+c+d}=\frac{b+c}{a+b+c+d}\times\frac{c+d}{a+b+c+d}
\\\iff &ac=bd.\end{align}

Imagine two events $X$ and $Y$ that are not mutually exclusive, such that $P(X) = 0.3 \,$ and $P(Y)=0.4.$ Consider their Venn diagram.
It should be clear that the only value of $P(X \cap Y)$ that makes $X$ and $Y$ independent is $P(X \cap Y) = 0.12.$

$$b=0.3-c\tag1$$$$d=0.4-c\tag2$$$$a=1-0.3-(0.4-c)=0.3+c\tag3$$
For events $X$ and $Y$ to be independent, $$ac=bd\tag4.$$
Solving $(1),(2),(3),(4)$ gives $$c=0.12,$$ as required.

Independence of events is not straightforward to intuit from Venn diagrams (unlike mutual exclusivity, which is observed by inspecting their intersection).
For example:

$$ \begin{array}{r}  \begin{array}{c|c|c}
  \style{font-family:inherit}{}  & \style{font-family:inherit}{U_1}  & \style{font-family:inherit}{U_2}  & \style{font-family:inherit}{U_3}
\\\hline
  \style{font-family:inherit}{P(X\cap Y)}  & 0  & \frac14  & \frac14
\\[0pt]\hline
  \style{font-family:inherit}{P(X)P(Y)}  & \frac14\times\frac12=\frac18  & \frac14\times\frac34=\frac38  & \frac12\times\frac12=\frac14
\\[0pt]\hline
  \style{font-family:inherit}{\therefore X\text{ and }Y\text{ are}\ldots}  & \textbf{dependent}  & \textbf{dependent}  & \textbf{independent}
 \end{array}\hskip-5.5pt  \end{array} $$
[Universe $U_1$ above is also an example of the fact that for events with nonzero probabilities, $\big(\text{mutual exclusivity}\implies\text{dependence}\big)$.]
Two more examples, but involving $3$ events: in each case, events $A,B$ and $C$ are pairwise independent yet not (mutually) independent $\big($since $P(A \cap B\cap C) \neq P(A)P(B)P(C)\,\big):$

When the probability experiment has just $2$ trials, a table like this is a good way to understand/visualise conditional probability as working in a reduced sample space:
$$ \begin{array}{r}  \begin{array}{c|c|c}
  \style{font-family:inherit}{\text{time of complaint}\bigg\\ \text{reason for complaint}}  & \style{font-family:inherit}{\textbf E\text{lectrical}}  & \style{font-family:inherit}{\textbf M\text{echanical}}  & \style{font-family:inherit}{\textbf L\text{ooks}}
\\\hline
  \style{font-family:inherit}{\textbf D\text{uring guarantee period}}  & 18\%  & 13\%  & 32\%
\\[0pt]\hline
  \style{font-family:inherit}{\textbf A\text{fter guarantee period}}  & 12\%  & 22\%  & 3\%
 \end{array}\hskip-5.5pt  \end{array} $$
The calculation (notice that the figure '$32$' was obtained from the intersection of column $L$ and row $D$) $$P(L|D)=\frac{P(L\cap D)}{P(D)}=\frac{32}{18+13+32}=51\%\neq32\%+3\%=P(L)$$ shows that $L$ and $D$ are dependent events.
Comment: Also see: [independence intuition](https://math.stackexchange.com/a/3906860/21813)
Answer: click to see diagramThe accepted answer by @Stats Data Enthusiast is certainly relevant, but I beg to differ on the question of whether it is possible to represent independence with Venn diagrams. The crucial observation is to use the area of the Venn diagram to represent a product of two, linearly independent, measurable subspaces.
Let the universe of the Venn diagram be a unit square in the Cartesian plane, and let the unit intervals in the X and Y axes be probability spaces of their own. Just really skinny - lengths rather than areas. Then the unit square is the product of those two subspaces, and the area measure is the product measure.
The two events identified in the original question with probability .3 and .4 would be represented on each axis as a segment of length .3 on on the X-axis and .4 on the Y-axis. Within each respective unit interval, each event has the stated probability. Let each sub-interval begin at the origin, (0,0).
Next consider the regions formed by treating each sub-segment as the short side of a rectangle - a region within the unit square, whose long side is the adjacent unit interval on the other axis, from (0,0) to (0,1) or to (1,0) respectively. In the theory of product spaces these rectangles are called cylinders, because they have a subset on one side and a whole space as their other side. In a probability space, the whole has measure 1, so the area of a cylinder is numerically equal to the length of its short side.
Now it's easy to see that the intersection of these two rectangles (cylinders) is a smaller rectangle with area .3 * .4 = .12! So we have a perfect Venn diagram which demonstrates the independence of the two events. And meanwhile shows the relation between probabilistic independence and linear independence.


Android share only an image to facebook using intents

Question: As many know, it appears to be problematic to share image + text to facebook using the Android share intent dialog. However, for the life of me, I can not get simple pure image sharing working.
After having tried everything I saw Android sharing from camera roll appeared to work. Hence the latest thing I have tried is this:
1)
contentUri_internal_fileprovider is a jpeg image save in internal storage.
Facebook share dialog turns grey and returns to my own acttivity)
    shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("image/jpeg");
    shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri_internal_fileprovider);
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(shareIntent.createChooser(shareIntent, "..."));

2
contentUri_camera_fromfile is a jpeg image save in camera storage.
Facebook share dialog opens but does not show any image)
    shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("image/jpeg");
    shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri_camera_fromfile);
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(shareIntent.createChooser(shareIntent, "..."));

For details on how camera roll image path is retrived:
      contentPathReal_camera_fromfile = MediaStore.Images.Media.insertImage(getContentResolver(), myBitmap, myTitle, myDesc);
      file_camera_fromfile = new File(contentPathReal_camera_fromfile);
      contentUri_camera_fromfile = Uri.fromFile(file_camera_fromfile);

Comment: Look at this : github.com/sromku/android-simple-facebook,it's provide easy way to integrate Facebook with your project
Comment: I will look into your suggestion (Facebook SDK solutions) if I can not get the Android intent working.
Comment: I have the exact same problem: saving image in internal store, provide URI from content provider, share only an image to fb => don't work (other apps work fine)
Answer: Here is what I tried, with the ByteArray and it worked for me. I tried using the putByteArray("photo", bytes.toByteArray());
private void publishStory() {
    Log.i("", "Got in publish story");

    final ProgressDialog progressDialog = new ProgressDialog(FacebookShareActivity.this);
    progressDialog.setMessage("Loading...");
    progressDialog.setCanceledOnTouchOutside(false);
    final Session session = Session.getActiveSession();

    if (session != null){
        progressDialog.show();
        // Check for publish permissions
        List<String> permissions = session.getPermissions();
        if (!isSubsetOf(PERMISSIONS, permissions)) {
             progressDialog.dismiss();
            pendingPublishReauthorization = true;
            Session.NewPermissionsRequest newPermissionsRequest = new Session
                    .NewPermissionsRequest(this, PERMISSIONS);
        session.requestNewPublishPermissions(newPermissionsRequest);
            return;
        }

        final Bundle postParams = new Bundle();
        byte[] data = null;
        Log.i("","Share pic :: "+sharePicture);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(sharePicture, options);
        if(bitmap != null) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        postParams.putByteArray("photo", bytes.toByteArray());
        postParams.putString("message", "I am supporting the "+candidateParty+
            " candidate "+candidate_name+" , competing for " +
            constituency+ " via BallotPetty®. - https://play.google.com/store/apps/details?id=com.cabot_technologies.elike");

        final Request.Callback callback= new Request.Callback() {
            public void onCompleted(Response response) {
                FacebookRequestError error = response.getError();
                progressDialog.dismiss();

                if (error != null) {
                    // Functionality : Do u Really wish to log out??
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(FacebookShareActivity.this);
                    alertDialog.setTitle("Alert");
                    alertDialog.setMessage(error.getErrorMessage());
                    alertDialog.setCancelable(false);

                    // Setting Positive Button
                    alertDialog.setPositiveButton(("Ok"),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
//                                      Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
//                                      startActivityForResult(intent, requestCode);
                                    dialog.dismiss();
                                    finish();
                                }
                            });

                    // Showing Alert Message
                    alertDialog.show();
            }
                else{

                    Toast.makeText(FacebookShareActivity.this, R.string.success_facebook, Toast.LENGTH_SHORT).show();
                    finish();

                }
            }
        };

        /*Request request = new Request(session, "343394662461234/feed", postParams,
                              HttpMethod.POST, callback);*/

          Request request = new Request(session, "me/photos", postParams,
                     HttpMethod.POST, callback);
          RequestAsyncTask task = new RequestAsyncTask(request);

          task.execute();

        }
        else
        {
            // Functionality : Do u Really wish to log out??
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(FacebookShareActivity.this);
            alertDialog.setTitle("Alert");
            alertDialog.setMessage("Null Image");
            alertDialog.setCancelable(false);

            // Setting Positive Button
            alertDialog.setPositiveButton(("Ok"),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
 //                             Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
 //                             startActivityForResult(intent, requestCode);
                            dialog.dismiss();
                            finish();
                        }
                    });

            // Showing Alert Message
            alertDialog.show();
        }
     }
}

Comment: Thanks - I will keep your solution. I still have a vague hope someone out there got Android intents working for sharing pure image (I doubt it though)


Draw graph of $\frac{1}{f(x)}$ from graph of $f(x)$

Question: If I know the graph of $f(x)$, how do I draw the graph of $\frac{1}{f(x)}$?
Answer: If you wish to sketch $y=\frac{1}{f(x)}$ given the graph of $y=f(x)$, some things to note are:

$f(x)$ and $\frac{1}{f(x)}$ have the same sign
$y=\frac{1}{f(x)} \implies \frac{\mathrm{d}y}{\mathrm{d}x} = -\frac{f'(x)}{f(x)^2}$; so $\frac{1}{f(x)}$ increases as $f(x)$ decreases and vice versa (minimum turning points become maximum turning points, etc.)
$x$-intercepts of $y=f(x)$ correspond to vertical asymptotes of $y=\frac{1}{f(x)}$
As $f(x) \to \infty$, $\frac{1}{f(x)}\to0$
If $f(x) > 1$, $0 < \frac{1}{f(x)} < 1$; similarly if $0 < f(x) < 1$, $\frac{1}{f(x)}>1$

This should make some sense with an example:

Note that the dotted horizontal lines represent $y=1$ and $y=-1$. The dashed vertical lines are asymptotes.
Comment: Ben, thanks very much for such detailed answer and picture!!
Answer: Any points where it's at $1$ or $-1$ will remain the same, so figuring out those will help.
Maxima will become minima and vice-versa, with $y$ value as the inverse of whatever they were before. Roots will become asymptotes (thanks to $1/0$), and vice-versa. Positive/negative will stay the same. I would find all the major features of the original function (roots, maxima, etc.) and invert those, connecting the graph smoothly. For example:
$y=x$. Has a root at $0$, which will become an asymptote. Reaches $1$ at $x=1$ and $-1$ at $x=-1$, and these points will stay the same. Positive/negative will stay the same. $y=x$ blows up to $\pm\infty$ on both sides, so inverting it should have it decrease asymptotically to zero in each case. It has no relative maxima/minima, so $1/x$ shouldn't either. This all taken together roughly suggests the proper hyperbolic shape of $1/x$. Similar ideas should work for more general functions.


Criar link com dados de um form

Question: Tenho um site externo de pesquisa pronto onde os resultados da busca geram um link semelhante a este: http://example.com/pesquisa?utf8=✓&search=itempesquisado&x=0&y=0.
Gostaria de criar um form no meu site que levasse para este link externo, ou seja, quando o usuário digitar itempesquisado no campo e clicar em enviar deve ser direcionado para a página: http://example.com/pesquisa?utf8=✓&search=itempesquisado&x=0&y=0.
Comment: Procure colocar mais detalhes na sua dúvida, como por exemplo o código html do seu formulário.
Comment: O problema é que se o código fonte estiver num encoding  diferente do servidor, e/ou o usuário usar browser com outro encoding ao preencher o form, não vai servir pra muita coisa saber como veio o ✓. Melhor examinar os headers e explicitar nos parâmetros se estiver usando este dado para detecção do encoding, e usar entities ( utf8="ç" no código-fonte, por exemplo. )
Answer: Tente este código HTML:

    <form method="get" action="http://endereco.com.br/pesquisa" enctype="application/x-www-form-urlencoded">
        <input type="hidden" name="utf8" value="✓">
        <input type="text" name="search" value="itempesquisado">
        <input type="hidden" name="x" value="0">
        <input type="hidden" name="y" value="0">
        <input type="submit" value="Pesquisar">
    </form>

Você poderá ter dificuldade para transmitir/receber este símbolo ✓ (%E2%9C%93), se você puder mudar ele, vai facilitar.
Comment: "Você poderá ter dificuldade para transmitir este símbolo ✓ "Mas de repente a idéia é justamente testar no servidor como o símbolo foi :)
Comment: Bacco, olhando a chamada acho que a intenção foi essa mesmo. Criatividade mil :D.
Comment: @AnthonyAccioly eu tentei deduzir a lógica, me pareceu o único motivo plausível :) em todo o caso, veja meu comment na pergunta sobre o risco de não funcionar como esperado.

Criar link com dados de um form


Random number generation in AnyLogic

Question: The code releases the first element of "wait", and randomly assigns the element to a service (simulator or gym), if there is space available in the service, based on certain conditions.
If a random number has been generated but it does not lead to a valid service, the code generates a new random number up to 100 times before breaking out of the loop.
if (wait.size() > 1 && (simulators.size() < 6 || Gym.size() < 15)) {
// Free the current wait and pick a service at random
wait.free(wait.get(0));
Random rand = new Random();
int iterations = 0;

while (true) {
    int randomNum = rand.nextInt(2) + 1;
    if (randomNum == 1 && simulators.size() < 6) {
        // Choose the simulator service if there's space available
        wait.get(0).var_simulatorService = true;
        break;
    } else if (randomNum == 2 && Gym.size() < 15 && wait.get(0).par_allowForGym == true) {
        // Choose the gym service if there's space available
        wait.get(0).var_Gym = true;
        traceln("The agent number " + wait.get(0)+ " Alllow to go Gym - " + wait.get(0).par_allowForGym);
        break;
    } else {
        // generate a new random number if the previous one didn't lead to a valid service
        iterations++;
        if (iterations >= 100) {
            traceln("The agent number " + wait.get(0)+ " Alllow to go Gym - " + wait.get(0).par_allowForGym);
            break;
        }
    }
}}

On the basis of this code when wait.get(0).par_allowForGym == false then the loop will run(100 times) unless the random value become 1, but based on this error that never happen and loop break.
Answer: You should never code while (true). Although you specify break conditions, it is bad practice because you can not debug this (as you now experience right here :) ).
Best avoid while loops altogether, there are only very rare cases where you need them.
Rewrite your code using a for-loop or some entirely different setup. In your case, you may want to try a switch syntax or simple if-else logic for the rand value.
Comment: i did try switch but i want to generate the random number once no condition gets true, and that is only possible using while or do while. What i did is i only run the while for 10 times, if still no condition gets true using the random generated numbers, then  the loop will be closed. now when " wait.get(0).par_allowForGym == false " then no condition matches for it does not matter how many times new random number gets generated. Kindly take a look at question i update it with new code.
Comment: Try simplifying the example, too much code to sift through. Boil it down so it can be understood within 30 sec or so :) All these conditions are too confusing... (by doing that, you likely find the issue yourself anyway :) )
Comment: (And you can *ALWAYS* code without while loops, you just need to think about it differently. This is similar to state charts: Never use "condition-based" transitions as you can always replace them with other constructs)
Comment: Feel free to repost and ask how to code what you need (showing what you did already and what you actually want to achieve)
Comment: I again edit the question with simple code kindly take a look.

Random number generation in AnyLogic


How can I enable hash in C++ Standard Library?

Question: I have tried using #include<hash_map> and #include <hash_set> and I still get the same errors.
Here is my code:
void HashTable_chaining::remove( const string & x )
{
    int hash_index = hash( x, theLists.size( ) ) ;

    list<string>&  whichList = theLists[ hash_index ];

    // search to make sure element not present
    for(list<string>::iterator itr=whichList.begin();itr!=whichList.end();itr++) {
        if(*itr==x) {
            theLists[hash_index].erase(itr);
            return;
        }
    }
    // element not found - so nothing to remove
}

And my errors are:
Error   8   error C2872: 'hash' : ambiguous symbol  c:\users\aaron           johnson\desktop\program 5(johnson- noakes)\program 5(johnson- noakes)\chaining.cpp 32  1   Program 5(Johnson- Noakes)

And I have 8 of these errors. Any suggestions? How can I find out which headers have to be included to use hash?
Comment: You didn't look through your C++ Standard Library reference, then?
Comment: You probably want `unordered_map` and `unordered_set`.
Answer: Is hash a function of your own?
If so, try putting it in a namespace of your own and then call the function like
int hash_index = yournamespace::hash( x, theLists.size() );

If you want to use the std::hash: It is defined in
#include <functional>

Comment: i tried int hash_index = std::hash( x, theLists.size() ); with functional included and i still got the same errors.
Comment: The usual scheme is to do `using std::hash; hash(whatever);`. Then it will use std::hash for types where that is defined, or use the user-defined hash function from the correct namespace for other types via argument-dependent lookup, without the user having to specifically name the namespace.
Answer: You can find the entire C++ spec here online, including our friend "std::hash":
http://en.cppreference.com/w/cpp/utility/hash
Comment: It should be noted that this is a C++11 feature.
Answer: hash_set and hash_map is available in the SGI STL. Take a look at the following pages:

http://www.sgi.com/tech/stl/hash_map.html
http://www.sgi.com/tech/stl/hash_set.html

The documentation and source code is available at this link:

http://www.sgi.com/tech/stl/download.html


How to add features of higher order for Logistic Regression

Question: I'm starting my first Machine Learning project to classify some entities and I decided to use Logistic Regression for the task.
Initially I starter with around 10 features and I can see that my model is underfitting the data (F-Score around 0.63).
That can be explained because all of my features are of first order and so my hypothesis is a first order polynomial.
I would like to add more of higher order features, but I quickly realized that I don't have a good intuition on how to do that. I could take each of my features $X_n$ and add new ones $X_{n^2}$, $X_{n^3}$ etc. I could also start adding more complex features like $X_1$ * $X_2$ etc.
Immediatelly I noticed that there are countless possibilities. How do I start? What are good practices in adding more features. How can I avoid overfitting the data?
Comment: Logistic regression is not a classification technique.
Comment: It's only appropriate to do that if you have a utility function, e.g., the costs of wrong decision in both directions.  When logistic regression was invented by DR Cox in 1958 it was to directly estimate probabilities.  For more see http://www.fharrell.com/2017/01/classification-vs-prediction.html .  As described there, one of the greatest mistakes made in machine learning is to develop classifiers when the appropriate solution is risk estimation.  There is a nomenclature problem in the reference you gave.  Probabilities can have nothing to do with classification.
Comment: @FrankHarrell why not? Seems like it's completely fine to treat the output hyphothesis from Logistic Regression to classify items. Example: https://www.cs.cmu.edu/~kdeng/thesis/logistic.pdf
Comment: @ŁukaszBachman This thread may be of interest. https://stats.stackexchange.com/questions/127042/why-isnt-logistic-regression-called-logistic-classification/127044#127044
Answer: If you are really want to create higher order features to a logistic regressor then I would suggest you expand your features with interaction  between features $X_1*X_2$, nonlinear features like $log(X_1)$ and $X_1^2$. Everything exactly like you proposed.
Finally to avoid over-fitting and at the same time doing variable selection apply a LASSO regularizer, it will both penalize model complexy and also induce sparsity. Only the subset of features, high order features that are of higher importance will be kept by the model.
You might also want to consider non linear models, they try to discover the optimal non-linearity by themselves (e.g. neural networks).
Comment: sounds sensible and thanks for mentioning LASSO, but again my question is - where do I stop? I can easily add $X_n^2$ but should I also add $X_n^3$, $X_n^4$, etc.? If I create new features that represent interactions like $X_1* X_2$, should I then also add $X_1* X_2^2$? Of course I could do that iteratively and stop when I'm satisfied with accuracy of my classifier, but that seems to be a too big job to be done manually.
Answer: First of all, it's important to know the number of entites you have.
The number of regressors you can have will be very dependent to that.
Have you split your data in a training set and a validation set ?
After, you're not necessarily "under fitting", maybe a model with a F-score of 0.63 is the best model possible.
Be careful to not add to many features, it will add variance to your model. To know which feature you have to keep, you have to use a significance test for every feature.
You can see here a example on R : http://www.r-tutor.com/elementary-statistics/logistic-regression/significance-test-logistic-regression
If there insignificant feature, you delete one by one the features with the higher p_value.
You will quickly see that the feature with a high polynomial degree are often insignificant.
Answer: Your best guess to 'where to stop' is to continuously plot your metrics (precision/recall/accuracy/misclassification) with your test set. As soon as they start to deteriorate you're likely overfitting and might want to reduce the number of features. Also, you have to use your intuition while selecting which polinomial features to add. Prioritize the features that seem to be more relevant.
See the error-analysis section here: http://www.holehouse.org/mlclass/11_Machine_Learning_System_Design.html
Also, another way to add features that might improve the algo is to breakdown factor/categorical features into dummy features (https://discuss.analyticsvidhya.com/t/how-to-handle-categorical-variables-in-logistic-regression/247/4)
Hope this helps
Comment: Does this really relate to logistic regression?


"Probability" of a map being surjective

Question:
What is the probability of randomly putting $n$ elements into $k$ boxes ($k\leq n$) such that there is no empty box?

I have two different ideas:

I could use the principle of inclusions and exclusions with $A_i=\{\text{box $i$ is empty}\}$: \begin{align}P(\text{no empty boxes})&=1-P\left(\bigcup_{i=1}^k A_i\right)=1-\sum_{i=1}^{k-1} (-1)^{k-1} \binom{k}{i}\left(\frac{k-i}{k}\right)^n\\&=\sum_{i=0}^{k-1}(-1)^k\binom{k}{i}\left(\frac{k-i}{k}\right)^n\end{align}
There are $\binom{n+k-1}{k-1}$ different ways of putting $n$ elements in $k$ boxes. Putting the elements in such that no box remains empty should be the same as putting $n-k$ elements in $k$ boxes i.e. $\binom{n-1}{k-1}$. So the probability that no box is empty should be \begin{align}P(\text{no empty boxes})&=\frac{\binom{n-1}{k-1}}{\binom{n+k-1}{k-1}}\end{align}

The two solutions are different. I'm pretty sure the first on is correct. Where is the mistake in the second one? Is the problem that the different ways of putting the elements in the boxes are not equal-probable? Can I fix the second attempt somehow?
Comment: I don't follow you on some things in the second approach. If we have 10 boxes and 12 things, how is putting the things in so none are empty analagous to puttint $n-k=12-10=2$ things into 10 boxes? I think you're assuming that during the first ten placements the bins get filled, and then you put the remaining two somewhere. But I'm not seeing why you can assume that the boxes get filled as soon as possible. And I also don't see your n-1 choose k-1 as being the number of ways to put n-k things into k boxes.
Comment: In the second approach I ignore the order, the elements get put in (may be that's the problem, why the different ways are not equal-probable). So I'd argue putting 12 elements in 10 boxes with the constraint, that all boxes get filled, is the same as putting 2 elements in 10 boxes. The number of ways of doing is is $\binom{n-1}{k-1}=\binom{11}{9}$ since I can view the ten boxes as $9$ barriers and putting 2 elements in 10 boxes as choosing 9 barriers out of $2+9=11$ elements.
Answer: To see what's wrong with the second approach, look at the case $n=k=2$. Call the $2$ objects $a$ and $b$. The $4$ equally likely outcomes are:
$$\begin{array}{c|c}
\text{Box }1&\text{Box }2\\ \hline
a,b\\
a&b\\
b&a\\
&a,b
\end{array}$$
Clearly the desired probability is $\frac12$.
When you say that there are $\binom{2+2-1}{2-1}=3$ possible distributions of the $2$ objects amongst the $2$ boxes, you're talking about indistinguishable objects: the second and third cases in the table above are counted as a single distribution of the objects. The appropriate table is now this one, in which only one of the three distributions has objects in both boxes.
$$\begin{array}{c|c}
\text{Box }1&\text{Box }2\\ \hline
x,x\\
x&x\\
&x,x
\end{array}$$
Your second calculation gives the probability that a randomly selected distribution of $n$ indistinguishable objects amongst $k$ boxes has no empty boxes.
In your case the objects being distributed really are distinguishable: there's a difference between the identity function on $\{0,1\}$ and the function $f(x)=1-x$, though both are surjective. Your second calculation, however, treats these as the same function: each puts one object in each of the two boxes, so to speak.
Comment: Thank you! I think I got it. So the first calculation is correct?
Comment: @Julian: You're welcome. Yes, it looks okay. (And even if I missed some minor algebraic error, the *method* is definitely okay.)

"Probability" of a map being surjective


Integrating a poisson rate

Question: I am completing some practice questions, in which I have been asked the following.
My query is with the solution, in which we integrate our poisson process rate. There is no explanation in my notes provided as to why we perform this. The answer begins as follows:

I understand how to derive my solution, but I am a bit unsure as to why we integrate the poisson rate we have? I can't find anything explaining the integral of a poisson rate.
TIA.
Answer: In a regular Poisson process, the rate is a fixed real number $\lambda$, such that $\mathbb P(N(t) = n) = e^{-\lambda t}\frac{(\lambda t)^n}{n!}$ for $n=0,1,2,\ldots$. In a non-homogeneous Poisson process, the rate is a function of time $\lambda(t)$. So to find the distribution of $N(t)$, we integrate the rate function with respect to time to obtain the cumulative rate function. In this case,
$$
\Lambda(t) = \int_0^t \lambda(u)\ \mathsf du = \int_0^t k\rho e^{-\rho t}\ \mathsf dt = k(1-e^{-\rho t}).
$$
Note that in a regular Poisson process the rate function is $\lambda(t)=\lambda$, so integrating yields $\int_0^t \lambda\ \mathsf du = \lambda t$. Back to the problem at hand, we wish to find $t_0$ such that $\mathbb E[N(t_0)] = \lim_{t\to\infty}\mathbb E[N(t)] - \mathbb E[N(t_0)]$. Since
\begin{align}
\mathbb E[N(t)] &= \sum_{n=1}^\infty n\cdot \mathbb P(N(t) = n)\\
&= \sum_{n=1}^\infty n\cdot e^{-\Lambda(t)}\frac{\Lambda(t)^n}{n!}\\
&= \sum_{n=1}^\infty n\cdot e^{-k(1-e^{-\rho t})}\frac{(k(1-e^{-\rho t}))^n}{n!}\\
&= e^{-k(1-e^{-\rho t})}\sum_{n=1}^\infty n\cdot \frac{(k(1-e^{-\rho t}))^n}{n!}\\\\
&= e^{-k(1-e^{-\rho t})} k(1-e^{-\rho t})\sum_{n=0}^\infty \frac{(k(1-e^{-\rho t}))^n}{n!}\\
&= e^{-k(1-e^{-\rho t})} k(1-e^{-\rho t})e^{k(1-e^{-\rho t})}\\
&= k(1-e^{-\rho t}),
\end{align}
we have
$$
\lim_{t\to\infty} \mathbb E[N(t)] = \lim_{t\to\infty} k(1-e^{-\rho t}) = k,
$$
hence
$$
\mathbb E[N(t_0)] = k - \mathbb E[N(t_0)].
$$
It follows that $\mathbb E[N(t_0)] = \frac k2$, from which
$$
k(1-e^{-\rho t_0}) = \frac k2\implies t_0 = \frac{\log 2}\rho.
$$
Comment: This makes perfect sense thank you!
Comment: Glad I could help :)
Answer: I believe that the Poisson rate is expected number of decays per second as a function of time, and you are trying to determine the expected number of decays over some time period in order to calculate the half-life according to the definition in your problem.
Therefore, you need to integrate the $\lambda(t)$ to determine the number of expected decays.  From this result, you can determine the half-life, $t_{0}$, at which 1/2 of your expected decays have occurred.
I hope this helps.
Comment: Thanks for your help!

Integrating a poisson rate


How to print in decimal instead of hex using printf with esp-idf

Question: I am trying to print CAN bus messages that are received by an ESP32-S3 using the esp-idf framework. The provided example code for TWAI/CAN bus from the framework is shown below:
<code>printf("ID is %d\n", message.identifier);
if (!(message.rtr)) {
    for (int i = 0; i < message.data_length_code; i++) {
        printf("Data byte %d = %d\n", i, message.data[i]);
    }
}
</code>
If I send a CAN message with ID 123, it displays as 291, which is the same value but in hex. How can I specify the output format of the printf function?
I have googled and tried many solutions but I cannot seem to print the values in decimal.
Here is a link to the TWAI API reference for esp-idf
I have tried the following:
<code>    printf("%" PRIu32 "\n",a);
    printf("%lu\n", (unsigned long)a
</code>
But none seem to work.
Answer: val = 291 decimal:
printf("%d", val);
Outputs --> 291
printf("0x%x", val);
Outputs --> 0x123
The %x formatting variable tells printf to display the value as Hexadecimal. You can also specify the number of digits to display.
printf("0x%04x", val);
Outputs --> 0x0123


How to translate the description, and abstract metatag for the front page in a multilanguage site?

Question: I am using the metatag module. In admin/config/search/metatags I am controlling my metatags for my front page using Global:Front page. Here it is my configuration

How can I translate these metatags for other language. I can use tokens for the title but I don't know how to translate the description, and abstract metatag.
Any solution for this?
Answer: My solution was to install and enable  the Translation table module. Then follow these steps

go to admin/config/regional/translate/translate
then filter by metatag and it will show all the metatags that you can translate.

That's what it worked for me. If you have better solution please add it.
Answer: Solution 1: https://drupal.stackexchange.com/a/104829/21602
Solution 2: You can use views to generate front page. To use metateg in views you need to activate metateg views submodule.
7.x-1.1 version of metateg needs to apply patch https://www.drupal.org/node/1986032 for suupport i18n or use 7.x-1.x-dev version.
Answer: I use the context module to add meta tags in different languages to any page.
Create a context and select 'Require all conditions'
Add 2 conditions: path and language
Add 1 reaction: metatag
Configure conditions and reaction