UEFI PXE booting across subnets

Question: I'm trying to boot PCs from a Windows 2012R2 WDS server in UEFI mode. If, and only if, the client is in a different subnet from the DHCP/PXE servers, this fails with some of them. (It always works in BIOS mode, but I need UEFI.)
The symptom is that after the initial DHCP request/offer/request/ack sequence, the working clients contact the PXE server to get their boot information, and the failing ones do not.
There are two DHCP servers (also 2012R2) in addition to the PXE. There are no boot-related DHCP options configured on them; DHCP relaying is enabled on the network and relays to all three servers.
This is the packet list from booting a working client:
<code>1  DHCP Discover - Transaction ID 0xe828c4bc
2  DHCP Offer    - Transaction ID 0xe828c4bc (from first DHCP)
3  DHCP Offer    - Transaction ID 0xe828c4bc (from PXE)
4  DHCP Offer    - Transaction ID 0xe828c4bc (from second DHCP)
5  DHCP Request  - Transaction ID 0xe828c4bc (to first DHCP)
6  DHCP ACK      - Transaction ID 0xe828c4bc (from first DHCP)

7  4011 → 4011 Len=347                       (to PXE)
8  4011 → 4011 Len=349                       (from PXE)
9  TFTP Read Request, File: boot\x64\wdsmgfw.efi, (to PXE)
...
</code>
With a failing client, it looks exactly the same until line 6, then nothing more happens; it simply does not contact the PXE server.
I have compared the packet contents in Wireshark, and other than the values which are dependent on what network the client is on (giaddr, router, etc.), all the offers are identical between the working and failing cases.
This seems to affect particular BIOS/firmwares: The working clients include VMware Workstation and ESXi, as well as an Intel NUC, and it fails with Asus B150M-C mainboards and at least one Dell Optiplex. BIOSes are current, and at most a few months old, on all devices involved.
It looks to me like the UEFI firmware does not know how to use a router. Is there a way get this working?
Answer: The problem is the client; I should have looked more closely at my packet traces. I just figured out that right after it gets the DHCP ACK from the regular DHCP server, the failing client starts ARPing for the PXE server, getting nowhere, of course.
So the problem really is that the firmware does not understand routers.
Comment: Also, Asus has acknowledged the bug and is about to release a fix. Thanks for the suggestion, I will take a look at that.
Comment: Please explain why you think the UEFI firmware does not understand routers.   I am curious as to how you came to that conclusion.
Comment: To send an IP packet to a destination, you need its MAC address (at least with Ethernet). The way to determine that address is ARP; you send a request "whoever is 192.168.1.1, tell me your MAC address". ARP is not routable, so it works only in the connected network segment. If the destination for your packet is outside that segment, you need a router, and you send the packet with the destination IP address to the router's MAC. My mainboards here send ARP requests for the PXE server itself, even though the DHCP lease tells them it's outside their subnet.
Comment: Thanks.  Issue is probably specific to your mainboard firmware as you say.  However, Windows 2012R2 WDS is known to be temperamental w.r.t. EFI/UEFI booting.    I suggest you read 2Pint Software's White Paper "Using DHCP to Control UEFI & BIOS PXE".
Answer: your DHCP strategy is a mess. You should not have more than one DHCP server per net and the PXE server acting as proxyDHCP.
More than one DHCP server leads to race conditions; you cannot predict which DHCP will end up really providing the IP to the client.
you probably have some other DHCP in the second net and the proxyDHCP offer (PXE server) probably never gets to the other side.
You should carefully read the Wireshark capture; uploaded it somewhere and we can help.
Comment: I have one subnet with two DHCP servers and the PXE server. The clients are in another subnet. The PXE server, as I was careful to point out above, hoping to avoid this exact response, _is_ acting as proxy DHCP, because that is what port 4011 is. Having two DHCP servers does not lead to "race conditions", a term whose definition I would advise you to look up, but is useful to avoid service interruptions (simply put, with only one you'd better never need to reboot it) as long as  they are giving compatible answers, which mine do. The PXE offer would get through, were it ever requested.
Comment: 1) You are wrong; two DHCP offers leads to race conditions; the DHCP protocol has not provision for unequivocally taking 1 of the 2 offers; please read the corresponding RFCs. 2) Your redundancy DHCP strategy leads to having you know asking here whay your set up does not work. Upload your Wireshark capture.
Comment: 1) I do not need clients to take one specific offer. I need them to get at least one valid offer and take any one; I couldn't care less which one it is. 2) If you read my question past the first sentence, you will find that I mentioned that this _works with some clients_. Traces: https://www.dropbox.com/sh/mmfjrbobh45ausm/AAD_8mg92-JR7Ck7nqTo7cnNa?dl=0 (filtered: "(bootp||udp.port==4011||tftp.opcode==1)"). "Working" is cut after the first TFTP request to save space; it booted correctly after that. Traces are from the switch port the client is directly connected to.
Comment: 1) You said that there are no race conditions and I proved you wrong. so far we do knot know if your race conditions is not leading to alternative taken non absolutely equal offers. 2) It works with some clients because not all the DHCP client implementations are equal. If you want me to read your wireshark please remove your downvote.
Comment: Huh? I did downvote your (quite useless) answer, but I was then told that below 120 rep or something my vote wouldn't count. Are you sure that wasn't someone else? Anyway, I figured it out. After the client gets its DHCP ACK, it starts ARPing for the PXE server, so it clearly does not understand routers. I'm working on a workaround now; if that doesn't help, I'll see if I can do something with proxy ARP. No need to read the traces; I filtered out the ARP traffic anyway. Sorry for that.
Comment: Please.... your DHCP servers are assigning the same IP range to the local "and" remote network then sure you are going to have "routing" problems...
Comment: What on Earth are you talking about? Please go away.

UEFI PXE booting across subnets


DNS resolving incorrectly for some countries

Question: European visitors are being served an old version of the website - because it appears they are getting a site that is resolving to an ipv6 address.
Other countries resolve to the correct ipv4 IP.
My understanding of DNS routing is fairly limited - where can I fix this?
Comment: That's not really a good edit. The problem was not that some "countries" were being served a different version of your web site, but that anyone who had IPv6 was.
Comment: I'm voting to close this question as off-topic because it is too narrow in scope for the answers to be of use to the wider Internet community.
Comment: Thanks,  have edited the question to make is more general.
Answer: Shopify doesn't support IPv6 (which may be a big problem for you later) so just remove the old AAAA record. Your DNS records appear to be hosted by "Web-2u Limited".


$G$ must hit the origin. - Is this proof legit?

Question:
The map $F : \mathbb{R}^3 \to \mathbb{R}^3$ given by $F(x, y, z)=(-z, -x, -y)$ restricts to a map $f : S^2 \to S^2$ from the 2-sphere to itself.
Show that if $G$ is another map of Euclidean space to itself that restricts to $f$ on
the 2-sphere, then $G$ must hit the origin.

Assume for contradiction that $G$ does not hit the origin, then $G/|G|$ will extend to $F$ in the whole disk. Implying that $G/|G|$ has degree zero according to the proposition. Hence $F$ has degree 0, contradicts with the fact that $\deg F = -1.$

Proposition.
Suppose that $f: X \to Y$ is a smooth map of compact oriented manifolds having the same dimension and that $X = \partial W$ ($W$ compact). If $f$ can be extended to all of $W$, then $\deg(f) = 0$.

Thank you~~~~~
Answer: I think you are thinking right, but I would change some words:

Assume for contradiction that $G$ does not hit the origin, then
  $G/|G|$ is a function from the whole disk to the sphere. Implying that
  $f=(G/|G|)_{|S^2}$ has degree zero according to the proposition,
  contradicting with the fact that $\deg f = -1.$

Also note that in this case you don't need the general proposition: it's just the observation that a function from a sphere is contractible iff it extends to the disk. And if contractible then it is of degree $0$.
Comment: Looks great. Thank you savick!


How to use a custom deserializer with Spring @RequestParam

Question: I have an interface that's not aware of its implementations (module-wise):
public interface SomeInterface {
}

and an enum implementing it:
public enum SomeInterfaceImpl {
}

I have a @RestController:
@RequestMapping(method = RequestMethod.GET)
public List<SomeClass> find(@RequestParam(value = "key", required = false) SomeInterface someInt,
                            HttpServletResponse response){
}

Although Jackson is aware that it should deserialize SomeInterface as SomeInterfaceImpl as follows:
public class DefaultSomeInterfaceDeserializer extends JsonDeserializer<SomeInterface> {
    @Override
    public SomeInterface deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        return parser.readValuesAs(SomeInterfaceImpl.class).next();
    }
}

and:
@Configuration
public class MyJacksonConfiguration implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        if(bean instanceof Jackson2ObjectMapperBuilder){
            Jackson2ObjectMapperBuilder builder = (Jackson2ObjectMapperBuilder) bean;
            builder.deserializerByType(SomeInterface.class, new DefaultSomeInterfaceDeserializer());
        }
        return bean;
    }
}

and successfully serializes and deserializes SomeInterface as SomeInterfaceImpl in the @RequestBody, it doesn't seem to have any effect on mapping SomeInterface to SomeInterfaceImpl with @RequestParam. How do I overcome this?
Comment: converting request params doesn't use jackson (why should it it isn't json). You need a custom `Converter` for that which converts from a `String` to your implemenation.
Answer: Having a Converter in the application context as M.Denium suggested does the job:
@Component
public class SomeInterfaceConverter implements Converter<String, SomeInterface> {

    @Override
    public SomeInterface convert(String value) {
        return new SomeInterfaceImpl(value);
    }
}

Comment: No you don't. You just need a proper `Converter`.
Comment: not working method convert does not get invoked
Comment: Why should I explain an answer that I haven't given? How to register converters is explained in the documentation (which sadly people do not tend to read).
Comment: @M.Deinum Please explain?


Want to implement sticky local notification in React Native for Android

Question: Is there any way to keep a notification for an app stick to the lockscreen and notifications pull down in Android regardless the state of the application (running or killed) for example the Weather Channel App. But in react native.
I also want to have a custom notification with action buttons if its possible.
Answer: Use React native push notifications
If you want to make it sticky and needs custom actions, you can set like below
<code>PushNotification.localNotification({
    ongoing:true,
    actions: '["Yes", "No"]'
})
</code>
Check Custom action handling to handle your custom actions
Comment: This works only for Android. Is there any way to achieve the same for iOS?


how to create a small version of an image and display in original size when clicked in WebView?

Question: I am writing an application that loads up with local html pages.
My html pages include some images as well , I want to show these images in a custom size in default (say 400px * 200px) , and displays in original size when user clicked in .
For example this is my image tag in html doc:

What changes I must make to achieve the approach ?
Comment: that does not work @Reshma
Answer: Check this solution

Comment: thanks for your feedback , how can I add this code to my WebView , i meant how i must use jquery in my webview ? can you explain a little bit
Comment: in your view page itself you can add a script tag.  .Check the updated code
Comment: thanks, but that does not work , i copy whole code of yours and past to my html doc,even i enable javascript in my webView
Comment: @ShahinSoft have you enabled Javascript for webview like this:  WebView view =(WebView)findViewById(R.id.webview);
    WebSettings settings = view.getSettings();
    settings.setJavaScriptEnabled(true);
Comment: @Sanil yes i did it


How can I do a bootstrap distribution with R programming?

Question: I've been looking for a way to make a bootstrap distribution with R programming. Has R a pre-builded function to do that? what is standard procedure?
Answer: It can be done so easily with the R functions replicate and sample that there is not really a point in a function for that. This draws 2000 bootstrap samples from a heavily non-normal set of observations:
observations <-  c(1, 1, 1, 2, 1, 2, 1, 400, 401, 400)
bootstrapped <- replicate(2000, sample(observations, replace = TRUE))

You can inspect the first 15 bootstrapped samples
> bootstrapped[, 1:15]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
 [1,]    1  400    2    1    1    2  400  400    1   400     1   400     1     1     1
 [2,]    1    1    1    1    2    2    1  400    1     1     1     1   400     1     1
 [3,]  401    2    1    1    1  401    1    1    1     1   400     1   400     1   400
 [4,]  400    1    1    1    1    1    1  400    1     1     2     1     1     1     2
 [5,]    1  400  400    2    1    1    2  400    1     1   400   400   400   401   400
 [6,]    1  400    1  400    1  400    2    2    2     1     2     2   400     1   400
 [7,]    2    1    2    1    2    1    1    1    1   400     1     1   401     1     2
 [8,]    2    1    1    2    1    1  400    2    1     1     2     1   400   400     2
 [9,]    1    1    2    1    2  401    1    1    2     1     1   400     1   400     1
[10,]    1    1    1    1  400    1    1  400    1   401   401   401     1     1   400

Each column is a random replicate. Next, you probably want to apply some function to your samples. You can do that with apply with margin = 2. Let's compute a trimmed mean
trimmed.means <-apply(bootstrapped, 2, function(x) mean(x, trim = .1))
hist(trimmed.means)

All of that being said there are obviously packages on CRAN concerning bootstrapping that can easily be found via google. Which is usefull and when they are usefull will depend on what you plan to do in detail.
Read an introduction to the boot package in this article by A. Canty R-News Dec 2002: https://cran.r-project.org/doc/Rnews/Rnews_2002-3.pdf as an example.
For further questions consider that asking about how something is done in R or in SAS or in Python or in Julia is not on topic on CrossValidated (try StackOverflow for that). However what should be done statistics wise or why something should be done instead of the other usually is on topic on CrossValidated. It seems like a small thing but it will make the difference of a thread being closed or not.
Comment: There's a package `boot` *in the standard R installation* that supports bootstrapping, including some more sophisticated intervals like the studentised t and BCa.
Comment: I know. It is mentioned in my answer and a link to the R-Journal (back then "R-News") is contained in my answer.


a coprime triple and divisibility

Question: If we have $\left( a,b,c \right)=1$ then am i right in saying $\frac{a+b+c}{c}\notin \mathbb{N}$ and $c$ is coprime to $a+b+c$?  My reasoning being that there is no common factor that can be taken out of the sum to cancel with a factor in the denominator.  If $c$ wasn't in the numerator it would be a different story.
(the reason i ask is that my intuition using prime factors when dealing with these sort of problems in the past has lead me to incorrect conclusions - is it incorrect here?).
If the above is correct then based on similar arguments wouldn't $\frac{ab\left( a+b+c \right)}{c}\in \mathbb{N}$ imply $ab=dc$?  This seems intuitive to me since i can see that $a,b$ could possibly share different factors of $c$ in such a way that their multiplication forms a multiple of $c$.
Comment: To debug your reasoning we need to know precisely *how* you made the incorrect inference that $\,(a,b,c)=1\,\Rightarrow\, 1 = (a+b+c,\,c) = (a+b,c).\ $ Please elaborate.
Comment: @BillDubuque Firstly thank you for linking to the other duplicate.  Secondly i think i can see where it is i am going wrong.  As you say I'm assuming that $\left( a,b,c \right)=1\Rightarrow \left( a+b,c \right)=1$, and P Vanchinathan example nicely demonstrates why that can't work.  I can see that now.  The reason I'm going wrong, is that i'm incorrectly assuming if $a,b,c$ share no common factors, there isn't a factor we can take out the front of $a+b+c$ to cancel with a factor in $c$.  This neglects the fact that even if $(a,b)=1$ then $a+b$ still might have a common factor with $c$.
Answer: Take $a,b$ to be coprime numbers then for any $c$ we have  $\gcd(a,b,c)=1$.
Now take $c>1$ to be a factor of $a+b$ (if prime, take $c$ as $a+b$).
Now $(a+b+c)/c$ will be an integer.
Example: $a=5,b=7, c=4$. There are examples not of this kind too:
$a=4, b=8, c= 3$.
Comment: Thanks for the reply.  I'm not sure where my reasoning is falling down here.  Consider https://math.stackexchange.com/questions/388560/is-the-sum-of-two-coprime-numbers-also-coprime-to-its-summands  why does the addition of a third number change the reasoning?
Comment: @user25025 That question is a dupe - now linked to many more answers which you may find helpful.
Comment: @BillDubuque Hi Bill.  Not sure i follow.  are you saying my question is a duplicate of the one i linked in my comment?  i'm guessing it probably is, but i just don't see why an argument along the lines of not being able to pull out a common factor across all three isn't enough to imply the sum isn't coprime to a summand (as P Vanchinathan's example demonstrates).  I guess another way would be to explain what condition i need for $a+b+c$ to be coprime to $c$.  Or am i making little sense?
Comment: @user25025 No, the dupe link is for the other question. I mentioned it here  since you may find the newly linked answers instructive.

a coprime triple and divisibility


If $a = b \; \text{mod} \; n$ and $c = d \; \text{mod} \; n$, then $a^c = b^d \;\text{mod} \; n$.

Question: I need help with getting on the right track for this one.
Since $a = b \; \text{mod} \; n$, we have that $a = kn + b$ for some $k \in \mathbb{Z}$. Likewise, we have $c = jn + d$ for some $j \in \mathbb{Z}$. Therefore, we must show that $n | a^c - b^d$. However, we can substitute $(kn+b)$ for $a$ and $jn+d$ for $c$ to get $(kn+b)^{jn+d} - b^d$. By the binomial theorem, we have $\sum_{i = 0}^{jn+d} \binom{jn+d}{i}(kn)^{i}d^{jn+d-i} - b^d.$ It is at this point I get stuck though. Am I on the wright track, or is there a much easier way?
Edit: A slight modification, the homework did say $a,b,c,d$ were all positive integers.
Comment: What makes you think it's true? Have you tested it?
Comment: It's an assignment from the homework, so I assumed it to be true. I guess I shouldn't trust that though
Comment: Perhaps it was asked as a question (i.e., "if ... must it be true that .. ?"), Or maybe it was phrased as "prove or disprove ...". In any case, the lesson here is if you're asked to prove something that's not obviously true, at least do some spot checks.
Comment: Double checking it, the way I phrased it is correct. Maybe it was a typo or an oversight.
Comment: If $a=b$ and 4d=c+n4 and 4\gcd (a,n)=14 then 4a^c\equiv b^d \pmod n \iff 0\equiv a^c(a^n-1)\pmod n \iff a^n-1\equiv 0\pmod n.$ When $a=2$ and $n=3$ we have $a^n-1=7 \not \equiv 0 \pmod 3$.
Comment: $3^2 \equiv 2 \mod 7$, $3^{2 + 7}=3^9 = (3^3)^3 = 27^3 \equiv -1^3 \equiv -1 \equiv 6 \mod 7$.  So for $3 \equiv 3 \mod 7$ and $2 \equiv 9 \mod 7$ it does not appear to be true.
Comment: Thing is... this implies $a^n \equiv a^0 = 1 \mod n$ which... if you are familiar with Eulers thereom isn't true in general.
Answer: This is not true!  Consider $a = b=2$ $c = 0$, $d = 7$, $n = 7$.
Then $a^c = b^c = 1 \pmod 7$, but $a^7 = b^7 = 2 \pmod 7$
Comment: Ah, thank you so much!
Comment: What if we modify it so that a,b,c,d are all positive integers?
Comment: No, $2^1 \neq 2^8 \pmod 7$
Answer: The thing is... if this were true this would imply $a^{n+b} = a^na^b \equiv a^b \mod n$ and if $b=0 \implies a^n \equiv 1 \mod n$ which... doesn't seem right. In fact Fermat's Little Theorem and Euler's Theorem say it is not true.
Comment: Didn't I say that FLT --- faster than light travel--- Fermat's Little Theorem just what I wro.... oh, googly-moogly!


How to build a nested MongoDB query in java?

Question: I am trying to translate a working Mongo Shell query to java, but it seems like I have ran into a wall. I am using the mongo-java-driver:3.9.1. The shell query looks like this:
db.getCollection('xyz').find({source_id: ObjectId("abc"), timestamp: {
    $gte : ISODate("2019-04-05 18:24:00.000Z"),
    $lt: ISODate("2019-04-05 18:30:00.000Z")
    }
  })

The query includes two criterias: a matching source_id and timestamps between the two given dates.
My Java query looks like this (startDate and endDate are formatted Dates):
FindIterable<Document> cursor = collection.find(and(eq("source_id", new ObjectId("abc"))), and(gte("timestamp", startDate), lt("timestamp", endDate)));

Intellij gives me the message: "Cannot resolve method 'find(org.bson.conversions.Bson, org.bson.conversions.Bson)". Is this a logical error, or is building a filter like that not possible?
Comment: Are you using `spring-data-mongodb` repository ?
Answer: You are missing one and:
FindIterable<Document> cursor = collection.find(and(and(eq("source_id", new ObjectId("abc"))), and(gte("timestamp", startDate), lt("timestamp", endDate))));

The general idea is: think of every { as an encompassing and statement.


mysql limit with in clause

Question: SELECT *
FROM restaurant_rate
WHERE
    table_id IN (SELECT id_table FROM rTable WHERE restaurant_id = ?)
LIMIT 0, 10;

The number of the result of the inner select is not static. In this case, mysql scans only 10 rows searching one by one? Or scans whole table and returns top 10 rows?
The id_table is an index column of rTable.
Comment: You may need an index for `restaurant_id` as well in `id_table`
Answer: The way your query is written is quite inneficient, because it forces to evaluate the in clause for every row in your table. If there are many records in rTable that match the criteria (let's say 1000), every row in restaurant_rate will need to be compared with 1000 values before being accepted or rejected by the where condition.
I would rewrite your query like this:
select rr.*
from
    restaurant_rate as rr
    inner join rTAble as r on rr.table_id = r.id_table
where
    r.restaurant_id = ?
limit 0, 10;

Things you must consider:

You need indexes for the columns involved in the join and in the where condition.
Using limit without order by does not makes much sense; add an order by clause before the limit.
Comment: Thanks Barranka. Your answer "it forces to evaluate the in clause for every row in your table" is exactly what I wanted to know. Thanks.

mysql limit with in clause


Absolute Galois group of the p-adic completion of a valuation field

Question: Let $K$ over $\mathbf{Q}_p$ be an algebraic extension, not complete for $|\cdot|_K$  (the unique extension of $p$-adic norm $|\cdot|_p$ to $K$).
(For example, $K=\cup_n\mathbf{Q}_p(\zeta_{p^n})$ the cyclotomic extension of $\mathbf{Q}_p$.)
Denote $G_K$ the absolute Galois group of $K$. Denote $\widehat{K}$ the completion of $K$ under the norm $|\cdot|_K$, and $G_{\widehat{K}}$ its absolute Galois group.

The question is :

Question (a):    Is it true that $G_K\simeq G_{\widehat{K}}?$

This statement itself is very strange for me as I never heard it before (I should have if it is true...). But I wrote a proof, not difficultly, as follows.
So please give me some remarks or let me know whether I made some mistakes in the following proof of Lemma (b) and hence proof of (a).

My proof of (a):
Let $L$ over $K$ be a Galois extension with Galois group $G$ and denote similarly $|\cdot|_L$ the unique extension of $p$-adic norm to L. Then I claim it suffices to prove

Lemma (b): We have $|\cdot|_L\circ g=|\cdot|_L$,  for any $g\in G$,  i.e. $G$ acts isometrically over $L$.

Let me first explain why Lemma (b) is enough: (the proof is classical) By Lemma (b) we will have $G_K$ acts isometrically over $\overline{K}$, hence any $g \in G_K$ maps Cauchy sequences in $\overline{K}$ again to Cauchy sequences. Hence it extends to an automorphism of $\widehat{\overline{K}}$ (the completion of $\overline{K}$ with respect to the unique extension of $|\cdot|_p$). This gives an injective map
$G_K \to Aut_{K}(\widehat{\overline{K}})$. Moreover this is surjective (and hence an isomorphism), since an automorphism must maps algebraic elements over $K$ again to algebraic elements. Finally by continuity one notices
$Aut_{K}(\widehat{\overline{K}})\simeq Aut_{\widehat{K}}(\widehat{\overline{K}})\simeq Aut_{\widehat{K}}(\widehat{\overline{\widehat{K}}})\simeq G_{\widehat{K}}$.
(If we denote typically $\widehat{\overline{K}}$ by $C$, then summarize:
$G_K \simeq G_{\widehat{K}}\simeq Aut_{\widehat{K}}(C)$.)
Now we prove Lemma (b):
Proof of (b): Observe that $|\cdot|_L\circ g$ and $|\cdot|_L$ give two norms over $K$ that both extends $|\cdot|_K$ over $K$, and hence they both in particular extends $|\cdot|_p$ over $\mathbf{Q}_p$. Hence they must be the same by the unique extension of norm (not for $|\cdot|_K$ but for $|\cdot|_p$.)
Remark: Intuitively this Lemma (b) is wrong, since usually to prove this kind of arguments one always uses the completeness of the base field $K$ and then argue that the two norms (comes from the two sides of the equality in Lemma (b)) must be the same by the unique extension of norms. While here exactly we assume the base field $K$ to be not complete.

Edit: From the excellent comment of Torsten Schoeneberg, this "phenomenon" could be explained naturally by the basic fact "algebraic extensions of Henselian fields are still henselian".
Comment: Note that you can rewrite your proof of b to showing that for every algebraic extension of a local field, the valuation still extends uniquely to ("further") algebraic extensions. The concept that will clarify this is "[Henselian](https://en.wikipedia.org/wiki/Henselian_ring)". In particular, local fields are Henselian, and algebraic extensions of Henselian fields are Henselian.
Comment: @Torsten Schoeneberg This is already better than an answer I expected. By the way if you would like to simply copy and paste your comment as an answer, I will accept it.
Comment: @Torsten Schoeneberg Thank you for your patience to read this long question and give this excellent remark! This basic fact of "*algebraic extension of Henselian fields are Henselian*"  explains perfectly why my "seemingly basic but strange" statement (in the point view of local fields)  is indeed true, and indeed basic. I guess when I learned valued fields the local fields were too emphasized and most results were given in that setting without reaching the full generality.
Answer: Note that you can rewrite your proof of b to showing that for every algebraic extension of a local field, the valuation still extends uniquely to ("further") algebraic extensions. The concept that will clarify this is "Henselian". In particular, local fields are Henselian, and algebraic extensions of Henselian fields are Henselian.


Cannot access updated value

Question: Hello Am i need of some assistance here am stuck,tried to serach for solution on SO but cant find a solution ,Am learning react so decided to create a todo app.However i have been stuck when it comes to crossing off completed tasks. when i add a task i have a variable called tasks which basically is an object containing all the tasks in the following fomart:
enter image description here
Inside my app i have the following snippet of code
 const FILTER_MAP = {
  all_items:() => true,
  Active: task => !task.completed,
  Completed: task => task.completed
};

const FILTER_NAMES = Object.keys(FILTER_MAP);

function App(props) {

  const [tasks, setTasks] = useState(props.tasks);
  const [filter, setFilter] = useState('all_items');

  function addTask(name) {
    const newTask = {id: "todo-" + nanoid(),name: name, completed:false}
    setTasks([...tasks, newTask]);
  }

  function toggleTaskCompleted(id) {

    const updatedTasks = tasks.map(task => {
      // if this task has the same ID as the edited task
      if(id === task.id) {
      // use object spread to make a new object
      // whose `completed` prop has been inverted
      return {...task,completed: !task.completed}
      }
      return task;
    })
    setTasks(updatedTasks);
  }

  function clearCompletedTasks(){
     const completed = tasks.filter(task => task.completed === false)
     setTasks(completed);
  }

   const taskList = tasks
   .filter(FILTER_MAP[filter])
   .map(task => (
     <Todo
       id={task.id}
        name={task.name}
        completed={task.completed}
        key={task.id}
        toggleTaskCompleted={toggleTaskCompleted}
        clearCompletedTasks={clearCompletedTasks}
     />
   ));

   const filterList = FILTER_NAMES.map(name => (
    <FilterButton
      key={name}
      name={name}
      isPressed={name === filter}
      setFilter={setFilter}
    />
   ));

  const tasksNoun = taskList.length !== 1 ? 'items' : 'items';
  const headingText = `${taskList.length} ${tasksNoun} left`;

  return (

Todo

                 <Form addTask={addTask}/>

                      <li className={`todo-item ${ tasks.completed ? "completed" :'' }`} >{taskList}

{headingText}

{filterList[0]}

{filterList[1]}

{filterList[2]}

XClear Completed

  );
}

export default App;

Todo
export default function Todo(props){

     return (

               {props.name}

            <input id={props.id}
                type="checkbox"
                defaultChecked={props.completed}
                onChange={() =>
                 props.toggleTaskCompleted(props.id)}
            />

    );
}

Problem
When i click on checkbox to indicate the task is done i can see that the value in completed is updating to true as show below
enter image description here
However when i try to evaluate and apply the following css its not working.
<li className={`todo-item ${ tasks.completed ? "completed" :'' }`} >{taskList}

How can i implement this so that "completed" style class is used when the state of completed value changes to true.Thank you
Answer: The problem is that you use a const to store an array which gets changed.
The correct thing to do would be the following:

{tasks
   .filter(FILTER_MAP[filter])
   .map(task => (
     <li class={`todo-item ${ task.completed ? "completed" :'' }`}>
     <Todo
       id={task.id}
        name={task.name}
        completed={task.completed}
        key={task.id}
        toggleTaskCompleted={toggleTaskCompleted}
        clearCompletedTasks={clearCompletedTasks}
     />

   ))}

Answer: This looks like a case of stale state. When your function closes over an old state (think closures), then whenever called in future it has access to the old state itself. Similar question
Check if moving your {tasksList} code inside the return method helps:

 <li className={`todo-item ${ tasks.completed ? "completed" :'' }`} >{
tasks
   .filter(FILTER_MAP[filter])
   .map(task => (
     <Todo
       id={task.id}
        name={task.name}
        completed={task.completed}
        key={task.id}
        toggleTaskCompleted={toggleTaskCompleted}
        clearCompletedTasks={clearCompletedTasks}
     />
   ));}

Comment: Thank you @Tsushar Shahi,for your response,unfortunatley no luck,will try to revise and research more as i wait for some suggestions
Comment: Ok. Can you add more of your code? Where is the  and probably more from your App.js where all of this logic lies.
Comment: done,hope thats helps.Thanks for your help

Cannot access updated value


In jazz, what is a chord family?

Question: In the jazz context, what is a chord family? How is the concept used in improvisation, chord substitution, and re-harmonization? Which are the families and their members?
I've seen chords divided in families and grouped by quality (Maj family, Dominant family, etc) or by function (like Tonic family = I, vi, iii Subdominant family = IV, ii Dominant family = V, viio) or by key (C, Dm, Em, F, G, Am and Bo = C maj family).
Are there other chord families?
How can this grouping help us with improvisation, chord substitution, and re-harmonization?
Comment: Google buddy - https://www.google.co.nz/search?q=jazz+chord+family&rlz=1C1NOOH_enNZ548NZ548&espv=2&tbm=isch&tbo=u&source=univ&sa=X&ei=VnyXU4SBKcTRkwWQhYHwBA&ved=0CEIQsAQ&biw=1920&bih=995
Comment: @scrowler: The idea is that the SE results should come up in google searches, so questions on "basic" things like these are good.
Answer: A family of chords will be the same, basically, in just about any musical situation. Built up off the basic notes of a particular scale. As in Cmaj. 3 majors, built on I, IV and V, three minors, built on ii, iii and vi, and one half diminished, built on vii.So these will be recognised as C, Dm, Em, F,G,Am and Bo in key Cmaj. The same concept applies in minor keys, not forgetting that three different sets of notes comprise these so there will be differing chords dependent on which set is being used. In jazz, melodic minor is the more usual.
That takes care of the triads. Jazzers like extensions, so as well as 1,3 and 5 making up a chord, 7,9,11 and 13 will be brought into use. They will still be 'rooted' in the originals, and often notes will be omitted. As in 13th - leave out 5, and maybe 9 and 11. Still recognisable as a 13th.
Altered notes are also de rigeur, as in #/b 5 and #/b9. Again these will use the basic triad as,- well,- a basis. Tritone substitution has been discussed on this site before, often with reference to the dominant chord.
So, the families are as ever, but with additions and changes to the same old relatives as before.

In jazz, what is a chord family?


How to calculate this limit without L'Hopital rule?

Question: I want to evaluate the following limit without using the L'Hopital rule : $$ \lim\limits_{x\rightarrow 0^+}\frac{e^{x\ln(x)}-1}{x}$$
I know the answer is $-\infty$.
I can demonstrate that graphically and by using the L'Hopital rule.
Any hint would be appreciated and thanks.
Comment: Multiply and divide by $\log x$
Comment: e^(xln(x)) = x^x might help
Answer: Note that for $x\log(x)<1$,
$$e^{x\log(x)}\le \frac1{1-x\log(x)}$$
whereby we see that for $x\le 1$
$$\begin{align}
\frac{e^{x\log(x)}-1}{x}&\le \frac{\log(x)}{1-x\log(x)}\\\\
&\le \frac{e}{e+1}\,\log(x)
\end{align}$$
Inasmuch as $\log(x)\to -\infty$, we find that
$$\lim_{x\to 0^+}\frac{e^{x\log(x)}-1}{x}=-\infty$$
Answer: HINT
The key point is that $x\log x \to 0$ then
$$\frac{e^{x\ln(x)}-1}{x}=\frac{e^{x\ln(x)}-1}{x\ln(x)}\ln x$$


XPath: How to check if an attribute exists?

Question: Given the following XML, how do I write an XPath query to pull nodes where the attribute foo exists?:
<node1>
  <node2>
    <node3 foo='bar'></node3>
    <node3></node3>
    <node3 bar='foo'></node3>
    <node3 foo='foobar'></node3>
  </node2>
</node1>

Answer: Short and sweet:
//*[@foo]

Of course you should use a more specific expression. But with [@attributeName] you get all nodes which have that attribute.
Answer: Use the following XPath expression
//*[boolean(@foo)]

Comment: This was helpful in the case where it was part of a larger boolean expression, i.e. `//button[@id='foo' and boolean(@disabled)]`
Answer: If you use and xpath, this maybe can help you:
count(//*[@foo])

it will return count of node/child that have attribute foo


Changing Selected Text in UltraTextEditor

Question: I want to change value in SelectedText in Infragistics UltraTextEditor before calling Copy method.  However, each time I try to set new value, SelectedText becomes blank. I'm working in C#, Visual Studio 2013.
Here is code snippet:
            string textToAlter = this.externalMessageTextBox.SelectedText;

            if (textToAlter.Contains("\r\n"))
                textToAlter = textToAlter.Replace("\r\n", "\r");

            this.externalMessageTextBox.SelectedText = textToAlter;  // SelectedText becomes blank

Additional information:
The text to be copied is an HL7 (Health Level 7) message like the one below.  It needs carriage return and new line to make it readable as text in UltraTextEditor, but HL7 standard requires segments to be terminated with with carriage return only.  I wanted copied text to be formatted per HL7 standard, because users most commonly copy it for pasting in HL7 specific editor or parser.
Here is the example of text message:
MSH|^~\&|LLS|NI|CTI|TEST0001|199712291047||ORU|57341.002|P|2.2
PID|1|111296|111296||Test^Patient|||M||||||||||1000
ORC|RE|R6013121-4^CTI|6013121-4^LLS||||||19971229104734
OBR|1|R6013121-4^CTI|6013121-4^LLS|5763^VITAMIN     B12^L|||19951218000000|||||||19951219091841||||||||19971229104736|||F

Comment: what is the text in the textbox can you give an example? Do you have a part of the text selected or the whole text in the textbox?
Answer: this has nothing to do with the infragistics control in general
but you have to do it this way even tho i am not quite sure what you are doing...
        string textToAlter = this.externalMessageTextBox.SelectedText;

        if (textToAlter.Contains("\\r\\n"))
            textToAlter = textToAlter.Replace("\\r\\n", "\\r");

        this.externalMessageTextBox.SelectedText = textToAlter;

lets say the .text in the Textbox is "abc\r\n" the outcome would be
"abc\r"
Comment: Actually I do not have problem with text formatting.  The characters are replaced just fine.  I can change text itself without a problem, but not selected text.  Even if I want to set selected text to something simple like "This is a test", it won't let me do it.
Comment: your code is working fine for me i have to select the text and it replaces it, but i had to double the char "\" to "\\" in order to get it working


ASP.Net Webapp no performance improvement with huge server update

Question: i am running an ASP.Net webapp on a dedicated server and recently made a significant update to the server hardware. To my surprise there is absolutely no performance increase.
old server:
single xeon x3220
2 gigs of ram
Windows 2003 IIs6
database running on separate server, older xeon.
new server:
32 gigs of ram
raid 1 0 SSDs
Windows 2008 standard
IIs7
dual xeon x5660
DB running on same machine
Everything about the new server is significantly better and yet no improvement. We are making updates to the webapp itself but i am wondering what can be done from a server/IIS7 configuration standpoint to speed this thing up. It seems impossible to me that this webapp has zero improvement with this update.
Comment: Without any details of what your app does there's not much that we can offer up as to why you're not getting an improvement.
Comment: The webapp is a basic CRUD db application. Gets data, displays it, posts/inserts etc. We are optimizing the webapp, but my question is should this significant hardware update not effect performance at all?
Answer: First of all we need to clarify what you mean by no improvement. The key thing to remember with performance optimisations is to measure.
If your pages were only taking milliseconds to load before then they are probably taking 1 or 2 milliseconds less now. Just because it isn't noticeable to the human eye doesn't mean it's not happening.
Of course there's also the difference in performance between how fast the pages load and how many concurrent requests the server can handle. You may find that even if the server seems to be responding the same it can take more simultaneous users.
If your application is a basic CRUD app then adding more processor and memory probably wouldn't make a difference because that's not where your bottleneck is. I'd have expected moving the DB to the same machine to give you a bit of an increase but again this is down to how you measure it.
My advice would be to use performance counters to measure server load, analyse the IIS logs to check page response times and find where the problem is.
Comment: OK, so my measurements were extremely straight forward. No concurrent users. Single page request response time. In all cases the pages response time was essentially the same. Meaning milliseconds faster or slower.. randomly.  I would think moving the DB onto the webserver would speed things up as well. But i would also think switching to a SSD raid would also increase speed.
Comment: Once the application is compiled and in memory then it doesn't require any disk access. SSDs for the database server should make things faster. It depends how fast things were in the first place. One thing that might be worth looking at is this blog post: http://appfabriccat.com/2011/06/windows-20082008-r2-default-power-plan-of-balanced-can-increase-latency-and-reduce-throughput/
Comment: My point is this.. The code and specifically the DB queries need to be optimized. BUT SURELY increasing the server hardware capabilities should show SOME noticeably change in performance. These pages i am testing have response times in the seconds. not milliseconds. So even if the queries are completely unoptimized there is something to be said about MS SQL and Server 2008 if it cannot utilize increased hardware power.. AT ALL. The query should be effected by disk access and processing power at some level, ram as well.. And yet there is no effect. So what optimizations can be made in ii7 or SQ
Comment: Yeah in terms of disk access i am talking about the DB, which is on the same machine.
Comment: Does the application do anything like make webservice calls to external services? One thing to bear in mind is that for a single user the hardware changes are not that significant. A single request is not going to make use of multiple processors or a significant amount of memory. Also make sure that you are not using the first request to the server as something to measure with. ASP.NET compiles the web application on first request, and this cold start normally takes a few seconds. Does every request take a couple of seconds?
Comment: hi Matt, i appreciate your comments. I have intimate knowledge of the webapp. There are no external webservice calls. I have a good understanding of how ASP.Net works in terms of requests. I've done the testing and it is no more complicated then described above. "what can be done from a server/IIS7 configuration standpoint to speed this thing up" that is the original question. I have a very good idea how to optimize the application. What i don't know about is the server config. IIs7 etc. That is why i posted this on server fault and not stackoverflow.
Comment: yes almost all requests are 1 second or more.. I am not trying to figure out how to increase performance on specific requests. I am asking what can be done in iis7/MS SQL/Windows server 2008 that would ensure a general increase in performance. If updating hardware has absolutely no effect then i would say we have found a SERIOUS issue with IIs7 and windows 2008. I am not running a wait or timer on requests in the app. So failing code optimization, what can be done? How can a p3 and dual xeon have the same performance?
Comment: IIS/SQL and Windows Server are tuned for performance out of the box. There isn't anything that you can reconfigure that is going to make a significant difference for these, so I'm afraid tweaking your application is probably the only option
Answer: Was the server upgrade done because the app wasn't performing well enough?
Yes, all the things you describe should lead to a faster experience. That they didn't suggests... (jarring chord) that it's not the platform that has the scalability issue.
You need to profile your application. IIS can serve lots of requests a second without any serious optimization, and it's unlikely you'd have changed any default settings (right?) already, so... that leaves the app. Or the App framework (.Net, right? got compilation debug=false set already?)
As you're on IIS 7 now, my suggestion is that the first place you look is Failed Request Tracing (install the Tracing component), and then hook up a rule that targets any response code (100-599), get the FREB log and look at where the time is being spent (the Compact view is good for this). If you see a module taking a disproportionate amount of time, investigate it.
Look at the web logs - are you seeing more requests than you think you should? (It's surprising how often the answer is "yes" when looking at performance optimization). To the time-taken results indicate that yes, the server thinks performance is slow?
Is there  javascript on the page? Could this be a client performance perception problem?
If that doesn't provide enough depth, look at either instrumenting the app, or hooking up a profiler to it, to determine where the time is being spent.
The thing is, if updating hardware has no effect - and it looks like a serious upgrade - you're not hardware bound. You probably never were. Asking for "general speedup tweaks" is not what you need - you need to measure, change, test, iterate. Once you identify the cause, the solution is simple. But you're not there yet.


Prove the equalities

Question: I have to fine the following equality
$ \sum^{n-1}_{m=0} \frac{1}{(n-m)p} = neH_n$
where $H_n = 1 + 1/2 + 1/3 + .... 1/n$
My Solution:
$ \sum^{n-1}_{m=0} \frac{1}{(n-m)p} = \frac{1}{n} + \frac{1}{n-1} + \frac{1}{n-2} + ... + \frac{1}{1} = \frac{1}{1} + \frac{1}{2} + \frac{1}{3} + .. \frac{1}{n} = \sum^{n}_{m=1} \frac{1}{mp} $
$ \frac{1}{p}\sum^{n}_{m=1} \frac{1}{m}  = \frac{1}{p}H_n$
How can I proceed further to get $neH_n$
Comment: What's $p$? Where's the inequality?
Comment: $e = \frac{1}{np}$
Comment: p is a variable quantity. (actually probability of an event)

@reuns how come? Is there any reference for it?
Comment: That's what implies your equality... There is nothing else to say
Comment: I am sure that is not the case...$n$ and $p$ are both independent variables.
Comment: What is $e$? From what you wrote as $neH_n=\frac{1}{p}H_n$ I thought that $e=\frac{1}{np}$ You say it is not, then how can we help you if we know nothing about $e$?
Comment: $e$ is a simple mathematical constant. The value of $e$ is constant while $n$ and $p$ are varying, and independent terms.
Comment: OMG... extremely sorry I missed one subtle note somewhere in the text of the paper.... $p \approx 1/ne$ (where again e is the Euler's constant)...Thanks guys for your help

Should I delete the question or post this answer as a separate answer, since this is not a very complex problem or innovative solution?
Answer: OMG... extremely sorry I missed one subtle note somewhere in the text of the paper.... $p≈1/ne$ (where again e is the Euler's constant)...
Thanks guys for your help Should I delete the question or post this answer as a separate answer since this is not a very complex problem or innovative solution?

Prove the equalities


How to process url from user input?

Question: I am creating LinkedImage field, formatter and widget so that images can be linked to somewhere.
And I have an issue with the input. The user can set internal or external links like /node/1, <front> or http://www.google.com. But the Url object that is required for link render element has no method that would work with all of these.
The Url::fromUserInput will work with internal paths but not with <front>. The Url::fromUri() will work with http://www.google.com but not with <front> or /node/1.
So I had to implement logic to distinguish the format and also I had to add validation handler into the widget telling the user that the link has to start with forward slash or with http prefix.
But I do not like this approach. Seems like this is not how it is supposed to be done.
So how can I properly construct Url object from these three types of input?
Also another issue here is that if "malformed" URL is already set (ie. it hasn't been validated via my UI validation handler) then I will get WSOD and that is just really bad UX.
Plus, as you can see, <front> is not working with any of these methods whic hrequires additional logic.
Answer: I had the same problem, so please try this:
$url_object = \Drupal::service('path.validator')->getUrlIfValid($path);
$url_object->setAbsolute();
$url = $url_object->toString();

Comment: Seems to be working. Although links starting with www instead of http will return false. But I'm fine with that + I am using textfield ant not url since it does not work with internal paths ans so i have custom validation handler in place which ca ntake care of this.
Comment: what if :Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

How to process url from user input?


Can't add Windows Server 2019 as AD to domain replica error

Question: Context:
I've got a Windows domain with a Windows 2016 functional level.
Currently all the ADs (three) are based on Windows Server 2016 and up to date.
Problem:
I want to had a Windows Server 2019 as AD to the domain. I can join the domain but I can't promote the server as AD. The wizard, when you fill up the domain, pops out a red notification which tells me that there is a replica error.

Checked:
Based on my research I've checked that I have the SYSVOL Share as a msDFSR-ContentSet.
Based on repadmin /replsum everything is ok
Comment: You know what would be helpful? The actual error message.
Comment: Can you provide the output of the following powershell commands: (Get-ADForest).ForestMode and (Get-ADDomain).DomainMode
Answer: As stated in your post your domain is probably in the Windows Server 2016 Domain Functional Level. However your Forest functional level might be lower.
Verify your domain functional level via PowerShell:
(Get-ADDomain).DomainMode

Verify your forestfunctional level via PowerShell:
(Get-ADForest).ForestMode

Beware before upgrading your domain or forest functional level. It is almost impossible to roll back this operation!
Answer: As @eKKiM said the forest functional level was lower than the domain functional level.
Fixed with the command : Set-ADForestMode -ForestMode Windows2016Forest


interpreting my own data (negative confidence interval in epidemiology)

Question: Im trying to measure the absolute change between two means of systolic bloodpressure, and used a simple method for calculating the confidence interval between to means.
My goal is to estimate the absolute change for the TREND between 1980-2000. So to accomplish this im comparing the first and last year (i.e 1980 and 2000, which i already have an point estimate and 95%Cl for, achieved with proc STDRATE in SAS 9.4, using a backgroundpopulation of holland).
Now to the problem ->
For the year 1980 i have a point estimate with 95%cl for systolic bloodpressure at 94.9(73.1 to 120.8)
For the year 2000 i have a point estimate with 95%cl for systolic bloodpressure at 80.3(70.1 to 96.8)
So the absolute change is -14,6, this means that the asbolute decline is 14.6 with the calculated confidence interval of +/- 22,7 (normal distribution).
Here's the thing-> i cant make any sense of how to interpret an absolute decline of 14.6 (-8.1 to 37.3).
Since im trying to describe trends and already know that systolic hypertension have a decline with 14,6 estimates then how can i describe a lower limit of minus (-)8.1 if its already a decrease.
Hope that this makes any sense, its probably a more epidemiological question then a mathematical or programming one.
In desperate need of help :)!
Answer: You're thinking too hard! A "negative decrease" is just an increase. Your CI says "with 95% confidence, systolic pressure changed between -37.3 and 8.1"
Comment: Thank you. Truly instructive. Do you know any book on this specific subject, or does most books in statistic cover this topic?
Comment: Well, the stuff about "negative decrease is an increase" is just math. As far as hypothesis testing goes, I first learned statistics through an econometrics lens, from *Introduction to Econometrics* by Stock & Watson, and then later from *A Second Course in Statistics: Regression Analysis* by Mendenhall & Sincich. They both have a good deal about hypothesis tests. There might also be some good references here: http://stats.stackexchange.com/questions/31800/online-reference-for-review-of-introductory-statistics-material
Comment: For general stats, I've heard good things about *Statistical Models* by Freedman, *Statistics for Experimenters* by Box, *Statistics in a Nutshell* published by O'Reilly, *Statistics in Plain English* by Urdan.
Comment: So your saying that a confidence interval for the lower limit below zero is an actual increase? For all i know u might be fully correct, cant just understand it quite yet. Since most of my variables have an absolute change very close to zero my lower limits are all negative. How can it then be that both the lower limit and upper is greater then the point estimate. For example i just did BMI (body mass index), it showed an absolute decline of 8,6 (-11,2 to 44,1). How would u interpret this? Btw really appreciating ur help!
Comment: Yes. You're stuck in the terminology. A negative decline is an increase. The lower bound on your decline is an upper bound on your change, i.e. your increase. This is why it's generally easier to think in positive units, it can be confusing. BTW, your CI for change includes 0 so you can't reject the null hypothesis of zero change with 95% confidence.
Comment: Okey. Intuitively It feels that the absolute change is significant. Can it be that whenever an effect is significant, all values in the confidence interval will be on the same side of zero (either all positive or all negative). Can I therefore specify the direction of the effect. There are many situations in which it is very unlikely two conditions will have exactly the same population means. Therefore, even before an experiment is conducted, I know beforehand that the null hypothesis of exactly no difference is false. I might be wrong, if so please be sure to correct me.
Comment: You have not proved that they are equal. You've only failed to rule out the possibility that the means are equal, up to a 1 in 20 chance of having missed a difference.
Comment: Yes, having values on the same side of 0 is equivalent to having a test statistic above the rejection cutoff. I recommend you sit down with a pen and paper and prove this for yourself, it's a great exercise that really forces you to understand how hypothesis testing and CIs work.
Comment: And you've uncovered the problem with frequentist statistics: assuming the existence of a single true underlying parameter value tends to be conceptually problematic. This is why people have come to interpret "failure to reject exact equality" as "close enough to equality." All you're doing in the latter case is letting your textbook choose a formula for "close enough" based on sample size and some distributional assumptions. Sometimes that's what you want, other times it isn't.


Remote Desktop Server always showing login screen

Question: Usually if you connect to a Remote Desktop Session Host running on a Windows Server 2008 R2 you will be prompted for your credentials and if they are valid you will be logged in to your session directly.
On one of our servers everyone who logs on with RDP sees the usual Windows Logon Screen (green/blue background with username/password) after already entering them in the Remote Desktop Client. So, users are not directly logged in, but have to enter their credentials twice. It is only the case for this server. The server also is a Remote Desktop Connection Broker.
Is this behavior caused by a wrong setting or do you know how to get rid of it?
Answer: We have that enabled on our of our machines through a GPO.  Take a look at this setting: Windows Components/Remote Desktop Services/Remote Desktop Session Host/Security under Computer Configuration/Administrative Templates and look for this setting: Always prompt for password upon connection    Enabled
Answer: I had a wrong setting enabled: Session Host Configuration -> Select the connection -> properties -> Credentials tab.
Here you can choose where to always ask for credentials or take the credentials provided by the client.
Comment: I'm running Windows 7, how does that actually look like?
Answer: Check out his link. You can edit the RDP client connection to not display the first windows security logon box.
http://chall32.blogspot.com.au/2012/04/fixing-remote-desktop-annoyances.html
Comment: He was asking how to provide credentials before connecting via RDP and why one server was different than the others and why it was prompting for authentication a second time.


Get all Dates between 2 Dates Javascript

Question: I'm having trouble with a feature that's supposed to bring up dates between two dates
I have identified the error and it depends on the time of the start date.
function getDatesInRange(startDate, endDate) {
 const date = new Date(startDate.getTime());

 const dates = [];

 while (date <= endDate) {
  dates.push(new Date(date));
  date.setDate(date.getDate() + 1);
 }

 return dates;
}

const d1 = new Date(doc.travel_start);
const d2 = new Date(doc.travel_end);

getDatesInRange(d1, d2)

travel_end: "2022-03-23T20:00:57.118Z"
travel_start: "2022-03-20T05:59:57.118Z",
Correct output:
[
2022-03-20T05:59:57.118Z,
2022-03-21T05:59:57.118Z,
2022-03-22T05:59:57.118Z,
2022-03-23T05:59:57.118Z
]
If i change the timestamp of travel_start to hour 23 the last date of my array is missing
[
2022-03-20T21:59:57.118Z,
2022-03-21T21:59:57.118Z,
2022-03-22T21:59:57.118Z
]
I have tried to remove the timestamp from travel_start by .setHours(0,0,0,0) without success.
Comment: it is correct, in the last iteration start is bigger than end (11PM 23 March > 5.59AM 23 March)
Comment: @shutsman So i have to initialize the dates?  `start.setHours(0,0,0,0);`
`end.setHours(0,0,0,0);`
Or is there a better approach?
Comment: honestly it is not clear for my why the last date should be included if it is out of the range
Comment: You could do `dates.push(new Date(date.setDate(date.getDate() + 1)))`. ;-)
Answer: If you're not opposed to using external libraries, date-fns has a lot of useful functionality, including what you are looking to do.
example:
import { eachDayOfInterval } from "date-fns";

function getDatesInRange(startDate, endDate) {
    return eachDayOfInterval({
        start: new Date(startDate),
        end: new Date(endDate)
    })
}

getDatesInRange(d1, d2)

Otherwise, shutsman's answer seems to make sense.
Answer: you are on the right way
setHours could have an issue with timezone try to use setUTCHours;
and reset start and end dates before any calculations
try out:

function getDatesInRange(startDate, endDate) {
    const start = new Date(new Date(startDate).setUTCHours(0, 0, 0, 0));
    const end = new Date(new Date(endDate).setUTCHours(0, 0, 0, 0));

 const date = new Date(start.getTime());

 const dates = [];

 while (date <= end) {
  dates.push(new Date(date));
  date.setDate(date.getDate() + 1);
 }

 return dates;
}

const travel_start = "2022-03-20T05:59:57.118Z";
const travel_start2  ="2022-03-20T23:59:57.118Z";

const travel_end = "2022-03-23T20:00:57.118Z";

const res1 = getDatesInRange(travel_start, travel_end);
const res2 = getDatesInRange(travel_start2,travel_end);

console.log('res1', res1)
console.log('res2', res2)
Comment: if it helps mark as correct)
Comment: Your suggestion of using UTC is a good one, but then you fall back to local methods in the loop, consider `date.setUTCDate(date.getUTCDate() + 1)`. Going into DST the local day is less than 24 hours long so doesn't add a full UTC day, going out is the reverse. ;-)


Can SQL query do this?

Question: I have a table "audit" with a "description" column, a "record_id" column and a "record_date" column. I want to select only those records where the description matches one of two possible strings (say, LIKE "NEW%" OR LIKE "ARCH%") where the record_id in each of those two matches each other. I then need to calculate the difference in days between the record_date of each other.
For instance, my table may contain:
id   description    record_id    record_date
1    New Sub        1000         04/14/13
2    Mod            1000         04/14/13
3    Archived       1000         04/15/13
4    New Sub        1001         04/13/13

I would want to select only rows 1 and 3 and then calculate the number of days between 4/15 and 4/14 to determine how long it took to go from New to Archived for that record (1000). Both a New and an Archived entry must be present for any record for it to be counted (I don't care about ones that haven't been archived). Does this make sense and is it possible to calculate this in a SQL query? I don't know much beyond basic SQL.
I am using MySQL Workbench to do this.
Answer: The following is untested, but it should work asuming that any given record_id can only show up once with "New Sub" and "Archived"
select n.id as new_id
      ,a.id as archive_id
      ,record_id
      ,n.record_date as new_date
      ,a.record_date as archive_date
      ,DateDiff(a.record_date, n.record_date) as days_between
  from audit n
  join audit a using(record_id)
 where n.description = 'New Sub'
   and a.description = 'Archieved';

I changed from OR to AND, because I thought you wanted only the nr of days between records that was actually archived.
Answer: My test was in SQL Server so the syntax might need to be tweaked slightly for your (especially the DATEDIFF function) but you can select from the same table twice, one side grabbing the 'new' and one grabbing the 'archived' then linking them by record_id...
SELECT
    newsub.id,
    newsub.description,
    newsub.record_date,
    arc.id,
    arc.description,
    arc.record_date,
    DATEDIFF(day, newsub.record_date, arc.record_date) AS DaysBetween
FROM
    foo1 arc
    , foo1 newsub
WHERE
    (newsub.description LIKE 'NEW%')
    AND
    (arc.description LIKE 'ARC%')
    AND
    (newsub.record_id = arc.record_id)

Can SQL query do this?


Who do I change strings in an array?

Question: I'm getting a string from an asps page like this:
~/TestImages/media/9.jpg?width=443&height=388&ext=.jpg?id=92,
~/TestImages/media/8.jpg?width=506&height=337&ext=.jpg?id=91,
~/TestImages/media/jpeg-3.jpg?width=720&height=480&ext=.jpg?id=75,
~/TestImages/media/4.jpg?width=725&height=483&ext=.jpg?id=77,
~/TestImages/media/7.jpg?width=957&height=629&ext=.jpg?id=81,
~/TestImages/media/10.jpg?width=478&height=356&ext=.jpg?id=85,

Each has a line break "\r\n" though..
Want to create an array with just the URL's (ie. "/TestImages/media/9.jpg").
Trying:
$.ajax({
        url: url,
        success: function(data){
            var str = data.replace(/(\r\n|\n|\r)/gm,""),
                imgArray = new Array,
                tdata = str.split(",");

            // make random order
            for(var i=0; i < 13; i++){
                var randomNumber = Math.floor(Math.random()*tdata.length);
                imgArray.push(tdata.splice(randomNumber,1));
            }
            $.each(imgArray, function(i, item) {
                var tmp = "";
                tmp = item[0].match(/~(.*?)\.jpg/g, "$1");
                item[0] = tmp;
            });

        }
    });

Not having much luck changing the value inside the array..  anyone have a way to do this?
Answer: var arr = $.map(data.split(','), function(s) {
    return s.trim().split('?').shift();
});

FIDDLE
Answer: This seems to does the job:
var s = "~/TestImages/media/9.jpg?width=443&height=388&ext=.jpg?id=92, \
~/TestImages/media/8.jpg?width=506&height=337&ext=.jpg?id=91, \
~/TestImages/media/jpeg-3.jpg?width=720&height=480&ext=.jpg?id=75, \
~/TestImages/media/4.jpg?width=725&height=483&ext=.jpg?id=77, \
~/TestImages/media/7.jpg?width=957&height=629&ext=.jpg?id=81, \
~/TestImages/media/10.jpg?width=478&height=356&ext=.jpg?id=85";

var sa = s.split(",");
for(var i=0; i < sa.length;i++) {
  var first = sa[i].indexOf("/");
  var last  = sa[i].indexOf("?");
  sa[i] = sa[i].substring(first, last);
}

console.log(sa);

You can play with this code here: http://jsbin.com/ePevaWos/1/edit?js,console
Answer:
      $.ajax({
        url: url,
        success: function(data){
            var str = data.replace(/[\r\n])/g,""),//remove all line breaks
                tdata = str.split(","),
                imgArray = [];
        $.each(tdata, function(i, item) {
            var match = item.match(/~(.*?)\.jpg/)[1];
            imgArray.push(match);
        });

        //shuffle now if desired
    }
});

You may also be able to just write:
var imgArray = data.match(/~(.*?)\.jpg/g);

http://jsfiddle.net/pDD5G/
Answer: Se the docs of jQuery.each.
Javascript does not have references, so, you can't change the values of the elements of an array as you iterate over it.
So, what you have to do is create another array and while iterating, push values into it:
var dst = [];
$.each(imgArray, function(i, item) {
   dst.push(item[0].match(/~(.*?)\.jpg/g, "$1")[1]);
});

Answer: Why not just use String split instead of regex?
for (var i = 0;i < imgArray.length; i++) {
  imgArray[i] = imgArray[i].split('?')[0];
}

Who do I change strings in an array?


Is there a way to short a string length in C# with .net framework 4.0?

Question: I'm trying to create a 22x22 datamatrix. It has a max length of 43 alphanumeric characters in each position.
I have a url string with a length of 60. Is there a way to encode the string into another shorter string to reduce it's length so it will fit in the 43 character limit?
I can't use url shorteners because the app is designed to work without internet. Enter the string into a database and get a short id that references it's also not an option.
I tried base64 and hexadecimal encodings, but they return longer strings than the initial. Any ideas?
Update: (try to explain better the problem)
The problem is cause I have the size for the datamatrix limited to 22x22 (43 alphanumeric characters, 55 numeric) and if i add more doesn't fit in the print desing reserved size. I have a local app where the datamatrix is generated, and that need to works without internet (downloading server information on certain dates) and print the datamatrix. A server will respond when the url inside the datamatrix is readed by a qr reader app.
Comment: I think you'll need a bigger datamatrix. I might be able to fix this for you today, but next week you'll need a 75 character URL. And if you make that work soon it'll be 80. And then 100. You say this needs to work without internet... but these are URLs after all. They're not useful without some kind of network access. What about your own URL shortener that runs on the local network?
Comment: do you only need the ability to encode URLs?  a reduced alphabet could reduce the number of bits required per character.
Comment: You might want to read [What is the maximum length of a URL in different browsers?](https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers) - basically, urls are not limited by standard, but should be up to 2000 chars in length. So even If you could use some zipping algorithm on a string to get it shorter, I seriously doubt you can use something to get from 2000 chars to 43.
Comment: Yes, the problem is that, cause I have the size for the datamatrix limited to 22x22 (43 characters) and if i add more doesn't fit in the print desing reserved size. I have a local app where the datamatrix is generated, and that need to works without internet (downloading server information on certain dates) and print the datamatrix. A server will respond when the url inside the datamatrix is readed by a qr reader app.
Comment: 22x22 should be able to handle exactly 60 characters, unless that includes the border, in which case you still get 55 characters.
Comment: Also, can you assume case insensitive
Comment: Can you provide some sample URLs?
Comment: Example url: https://exampleurl.com/reader?q=AXG567ER&st=1005&c=34500
Comment: my problem is that the q parameter needs to be length variable and maybe it has 8 digits like the example or maybe it has 16(2x8) or 24(3x8) etc..
Answer: Characters in a string are just bytes and one character could be represented by 8bits to 32bits (or theoretically longer).  You should work with bytes instead of strings.
Comment: Thank you for your answer. I tried it, but the revert method doesn't return the same value that the initial input if there are numbers in the string. Also when i read the datamatrix with an qr code reader app, it doesn't recognize the encoded string.
Comment: what string with numbers?
Comment: This code doesn't work and will actually *lose* data. It will mangle the data in any case. `iso-8859-1` is the Latin1 codepage so it *can't* represent some characters. Those characters will be replaced by `?`. The bytes it returns correspond to that codepage only. UTF16 on the other hand requires *two* bytes. Using `Encoding.Unicode.GetString()` here can easily create garbage as some combinations will be invalid. Those will be replaced by `�`
Comment: @PanagiotisKanavos you are correct.  the utf-16 will lose the character if the two byte combination is not a part of the codepage
Comment: @JackSojourn in the example I posted `m`, something that is part of US-ASCII and clearly an alphabet character war lost.


How do the variables in .twig files work?

Question: I am using a theme based off awesome zymphonies theme.
I'm trying to use the site_logo variable from page.html.twig, but it doesn't have access to it, instead I have to use the page.header region, which somehow (I need clarification as to how) calls upon the code in block--system-branding-block.html.twig and there I can use site_logo.
So my question is why site_logo can only be accessed from that twig, and what would I need to do in order to use site_logo, or any other variable in any other twig file?
Answer: The site_logo block is available in the page.header region because that logo block itself is placed into that region using Drupal's block layout: mydrupalsite.com/admin/structure/block
Drupal's template/twig system is a set in parent and children type templates. So the page.header region/template may print {{ site_logo }} - but the contents of {{ site_logo }} are outputted in block--system-branding-block.html.twig
Blocks are placed in regions so you can't really access a block directly in page.html.twig unless you add it programmatically.
Probably what you are looking to do is place the site_logo block into the region which approximates the position you want it to be displayed. Then if you want to "fine tune" it you can override that regions template using the following naming convention:
my_drupal_theme/templates/region--[region].html.twig

E.g.
my_drupal_theme/templates/region--header.html.twig

Then maybe your region--header.html.twig file looks like:

  {{ site_logo }}

What can be really helpful here is knowing the basics of twig template naming conventions - and also turning on "twig template debugging" which gives you template names you can use to override.
https://www.drupal.org/docs/theming-drupal/twig-in-drupal/twig-template-naming-conventions
https://www.drupal.org/docs/theming-drupal/twig-in-drupal/debugging-twig-templates#s-enable-debugging
Just for completeness: if you did want to load the logo directly in your page.html.twig you could add it via a hook_preprocess_HOOK
@file my_drupal_theme/my_drupal_theme.theme

/**
 * Implements hook_preprocess_page().
 */
function my_drupal_theme_preprocess_page(&$variables) {
  $block_manager = \Drupal::service('plugin.manager.block');
  $plugin_block = $block_manager->createInstance('system_branding_block', []);
  $variables['site_logo'] = $plugin_block->build();
}


HTML TextArea Limiting the amount of lines

Question: I would like to have a textarea where users can enter a maximum of 255 digits and 5 lines of text. Then when they click on the "Post" button the text will be send to a different php file.
The text gets sent to the second php file and the limit of 255 digits works (maxlength="255"), but I can't get the limit on lines. I googled it, searched the forum and tried multiple things, but nothing works.
This is one of the things I tried.

<textarea name="message" placeholder="What's on your mind?" maxlength="255" data-limit-rows=true></textarea>

<input type="submit" value="Post">
</form>

Thanks
Comment: @fauxserious I would like to limit the amount of lines of text. That code I copied from someone else. Because I thought it would do that.
Comment: @fauxserious the amount of lines. This is a number not a width.
Comment: Are you limiting the number of carriage returns (times the user has hit enter) or the number of lines of text according to the width of the textarea?
Comment: ...According to textarea width?
Comment: But it can be affected by width. The number of lines you can fit in a width of 100px is different from the number of lines you can fit in 600px.
Comment: @fauxserious I understand that it can be affected by it. But why do you think I posted this? Stop asking me how to do it because if I knew that I wouldn't have posted this.
Comment: I'm not asking how to do it, I'm trying to get clarification to your question. This question can be interpreted in a few ways. I'll answer for you assuming you do not mean carriage returns...
Comment: I've asked this almost a month ago. I just want to limit the amount of lines a user can type.
Answer: The number of lines of text in a container is normally dependent on the dimensions of that container. Therefore, you'll need some information about the text inside of the textarea first.
We can assume that one character is the height of one line in the textarea. This is of course also dependent on the font-size and font-family of the characters in the textarea. Once we get these dimensions, we can check to see how many lines have been typed in the textarea. Unfortunately, we'll need to replicate some of this using a div with the same width as the textarea in order to check these numbers.

var textarea = document.getElementById('userinput');
var button = document.getElementById('checklines');

button.onclick = function(){
  var temp = document.createElement('div');
  temp.style.width = textarea.clientWidth + 'px';
  var style = window.getComputedStyle(textarea)
  temp.style.fontFamily = style.getPropertyValue("font-family");
  temp.style.fontSize = style.getPropertyValue("font-size");
  temp.textContent = 'X';
  document.body.appendChild(temp);
  var unit = temp.clientHeight; // height of one line
  temp.textContent = textarea.value;
  var lines = temp.clientHeight / unit;
  console.log(lines);
  temp.outerHTML = '';
}
<textarea id="userinput"></textarea>
<button id="checklines">Check Lines</button>


Dynamic weight for Blocks

Question: I want to change the block weight in sidebar for each page request, So the blocks position would be change for each request.
Is there any way to do it ?
Answer: Drupal 8 is providing a hook to alter the region template_preprocess_region, it would prepares values to the theme_region.Adding the following codes in THEMENAME.theme file would solve the problems,
<code>function themename_preprocess_region(&$variables) {
  if ($variables['region'] == 'sidebar_second') {
    $variables['elements'] = shuffle_assoc($variables['elements']);
    $content = '';
    foreach ($variables['elements'] as $key => $value) {
      if (is_array($variables['elements'][$key])) {
        $content .= \Drupal::service ('renderer')->render($value);
      }
    }
    $variables['content'] = array(
      '#markup' => $content,
    );
  }
}

function shuffle_assoc($list) {
  if (!is_array($list)) {
    return $list;
  }

  $keys = array_keys($list);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key) {
    $random[$key] = $list[$key];
  }
  return $random;
}
</code>
For more details, check here
Answer: For Drupal 7, you could use something like hook_block_list_alter to alter the blocks on the page. Keep in mind that you might also want to use something like that to make this work.
Alternatively, something for Drupal 8 too, you can create a (block) view that contains whatever you're displaying in these blocks in a single block and then just sort them randonly.

Dynamic weight for Blocks


Closed Form Solution to finite sum

Question: I'm looking for a closed form solution to
$$
\sum_{n=0}^{m-1} n^p z^n
$$
, where p is an integer and z is complex.
Many thanks!
Answer: Hint:
Let $D$ be the operator
$$D:=z\frac d{dz}.$$
We have
$$D\sum_{n=0}^{m-1}z^n=z\sum_{n=0}^{m-1}nz^{n-1}=\sum_{n=0}^{m-1}nz^n$$ and by recurrence
$$D^p\sum_{n=0}^{m-1}z^n=\sum_{n=0}^{m-1}n^pz^n.$$
Then
$$\sum_{n=0}^{m-1}n^pz^n=D^p\left(\frac{z^m-1}{z-1}\right).$$

The general solution will be of the form $$\frac{P(z)}{(z-1)^{p+1}}$$ where $P$ is a polynomial of degree $m+p$.

Closed Form Solution to finite sum


I can not create a user through the console PG::UndefinedTable: ERROR: relation "team_members" does not exist

Question: I can not create a user, I get an error.
I'm trying to add another model, but I can not connect it to the database, I'm getting an error and can not execute Rails db: migrate
team_members.rb
class TeamMember < ApplicationRecord
end

I'm trying to run a command in the console and create a user but I get this error.
TeamMember.create(email:"firstname.lastname@example.com")
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "team_members" does not exist
LINE 8:                WHERE a.attrelid = '"team_members"'::regclass
                                          ^
:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
                     c.collname, col_description(a.attrelid, a.attnum) AS comment
                FROM pg_attribute a
                LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                LEFT JOIN pg_type t ON a.atttypid = t.oid
                LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
               WHERE a.attrelid = '"team_members"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum
from /home/*/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.1/lib/active_record/connection_adapters/postgresql/database_statements.rb:63:in `async_exec'

schema.rb
ActiveRecord::Schema.define(version: 2018_09_12_142120) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "active_admin_comments", force: :cascade do |t|
    t.string "namespace"
    t.text "body"
    t.string "resource_type"
    t.bigint "resource_id"
    t.string "author_type"
    t.bigint "author_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["author_type", "author_id"], name: "index_active_admin_comments_on_author_type_and_author_id"
    t.index ["namespace"], name: "index_active_admin_comments_on_namespace"
    t.index ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id"
  end

  create_table "admin_users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "sign_in_count", default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet "current_sign_in_ip"
    t.inet "last_sign_in_ip"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["email"], name: "index_admin_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_admin_users_on_reset_password_token", unique: true
  end

end

Comment: How did you get this ? `team_members.rb`. Is this file under model directory ?
Answer: There is no team_members table on your database so you cannot create a TeamMember.
If you would like to create this one you might run this command (for example);
rails g model TeamMember email:string

It will generate the migration file (db/migrate/20180914074925_create_team_members.rb) and also app/models/team_member.rb
After rails db:migrate Then you now can create it through the console
Comment: Very grateful to you. Thank you!


#superfish ul also targets contextual links!

Question: I am using superfish menu in D7 as follows:

I have created a custom theme from scratch
in my page.tpl.php I have created a region for my main menu as:

<?php print render($page['main_menu']);?>

I place the superfish block inside the main_menu region and it appears in place, as expected.
I write my .css, but when I target #superfish ul, the contextual links are also targeted and styled! I suppose this is not the normal behaviour.

In all other modules I've encountered (including nice menus), contextual links are kind of greyed out and cannot be targeted with CSS, but in the context of Superfish menu they appear active and targetable as ever. They even get superfish classes applied to them.
What am I missing?
P.S. I am starting using #suckerfish ul:not(.contextual-links) :-O
Comment: Would the answer be different if problematic CSS would appear in Joomla, or any other CMS with superfish menu plugin? Looks like universal CSS thing.
Answer: Try targetting #superfish ul.menu. This should discriminate the menu from ul.contextual-links. (Double check the class for your menu by viewing the page source if this does not work.)
Comment: Ohh, how dumb am I :O thank you very much, I started using `#suckerfish .content ul` to bypass the contextual links. Such a simple solution, doh! Do you happen to know if this is the normal behaviour of superfish? (sth get's screwed up because contextual links also rely on js?!)


Problemas na consulta do MySQL

Question:

<form method="POST" class="w-100" action="pesquisa_diaria.php">

                Tipo de Venda
                   <select class="custom-select" name="tipo_vendas" required>
                     <option value=''>Selecione...</option>
                     <option value='caixa'>Caixa</option>
                     <option value='delivery'>Delivery</option>
                     <option value='null'>Todos</option>
                 </select>

                Tipo de Pagamento
                   <select class="custom-select" name="tipo_pagamento" required>
                     <option value=''>Selecione...</option>
                     <option value='cartao_credito'>Cartão de Credito</option>
                     <option value='cartao_debito'>Cartão de Debito</option>
                     <option value='dinheiro'>Dinheiro</option>
                     <option value='null'>Todos</option>
                 </select>

                 Data
                 <input id="datepicker" name="data"  width="276" required/>

<button type="submit" class="btn btn-success">Pesquisar</button>

</form>

Tenho um formulário que faz uma consulta no banco de dados, mas estou com problema nas opções "Todos". Quando seleciono essa opção, a consulta não traz nenhum resultado.
SELECT * FROM vendas WHERE DATE(date_created) = '2018-12-12'
AND tipo_venda = 'null' AND tipo = 'null' ORDER BY 'id'

Answer: Acho que quando você fala todos voce quer que ele selecione qualquer valor, se for o caso você precisa fazer algo do tipo:
$WHERE = array();
if( $_GET['tipo_pagamento'] != "null" )  // so coloca se nao for null
    array_push($WHERE,"tipo='{$_GET['tipo_pagamento']}'");

if( $_GET['tipo_vendas'] != "null" ) // so coloca se nao for null
    array_push($WHERE,"tipo_venda ='{$_GET['tipo_pagamento']}'");

$WHERE = count($WHERE) ? "AND ".join($WHERE," AND ") : "";

$qry = "SELECT * FROM vendas WHERE DATE(date_created) = '2018-12-12' {$WHERE} ORDER BY 'id'"

print $qry;

O codigo acima não foi testado, mas essa é a ideia
Comment: A resposta do Icaro está correta. A sua query não vem porque você está comparando 'null' (varchar) com NULL (valor de fato). Se sua tabela possui informações NULL a query deve fazer a comparação "WHERE CAMPO IS NULL" (exemplo) e não "WHERE CAMPO = 'NULL'" (interpretando o valor a ser comparado como varchar). Mas se você está querendo apenas trazer todos sem especificar qual, a resposta está correta.
Comment: Mas to achando também que minha query ta errada porque mesmo jogando o select direto no banco os resultados não vem quando e null,
Comment: Se você quer checar se o valor é `NULL` , tem que usar `IS NULL` - exemplo `tipo_venda  IS NULL`  ou `tipo_venda IS NOT NULL` [MYSQL-doc](https://dev.mysql.com/doc/refman/8.0/en/working-with-null.html)
Comment: to entendo, mas se na minha tabela nao tiver null nos campos, como faço pra trazer tudo
Comment: Nao coloque no `where`. Exemplo quero que venha todos os `tipo_venda` `NULL` ou `NOT NULL`:  `SELECT * FROM vendas WHERE DATE(date_created) = '2018-12-12' AND tipo_pagamento='meu tipo de pagamento' ORDER BY 'id'`
Comment: note que a query nao possui `tipo_venda`, isso porque quero qualquer `tipo_venda`
Comment: agora se voce quiser so os `tipo_venda` com valores **nao nulos**, ai voce coloca `tipo_venda NOT IS NULL`
Comment: vc diz fazer assim SELECT * FROM vendas WHERE DATE(date_created) = '2018-12-12' AND tipo_venda IS NOT NULL AND tipo IS NOT NULL ORDER BY 'id'
Comment: mas se eu escolher outra opção nao daria erro
Comment: isso, essa query vai retornar apenas os registros com algum valor (nao nulo) em `tipo_venda` e `tipo`
Comment: se voce fizer esta outra query `SELECT * FROM vendas WHERE DATE(date_created) = '2018-12-12' ORDER BY 'id'` ele vai pegar todos os registros independente de `tipo_venda` e `tipo`, ou seja eles podem ter valor valido ou nao
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/87008/discussion-between-vision-development-and-icaro-martins).

Problemas na consulta do MySQL


The best way to test if a returned string is null in Java

Question: I have a function that concatenate a set of strings like this:
StringBuffer sb = new StringBuffer();

sb.append(fct1());
sb.append(fct2());
sb.append(fct3());

Where fct1(), fct2() and fct3() should return a String.
The problem is that I must test the returned values like this :
sb.append(fct1() == null ? "" : fct1());

because I get an exception if the value is null.
The problem is that I have many instructions like this and, above all, I can't modify these functions that return the strings(fct1, fct2 and fct3).
Is there a solution that will "sanitize" automatically my strings?
Thank you.
PS: I created a function that can do it:
public String testNullity(String aString){
aString == null ? "" : aString;
}

so that I can call it like this:
sb.append(testNullity(fct1));
sb.append(testNullity(fct2));
...

Comment: StringBugger? Is this some new class? :-)
Comment: Try to redesign your functions so that they do not return null values. That's the *best* way to avoid unexpected NPEs ...
Comment: So why does your solution not suit you?
Comment: @Howard StringBuffer is final
Answer: Another alternative might be
 public class SafeStringBuilder  {
    private StringBuilder builder = new StringBuilder();

    public SafeStringBuilder append(String s) {
        if (s != null)
            builder.append(s);
        return this;
    }
 }

Comment: Apart from `StringBuilder` being `final`, this is a nice idea. (Use delegation instead.)
Comment: Does not work, StringBuilder is final. Try the wrapper solution! (Edit: +1 for Paulo for being 11 seconds faster than me :))
Answer: If you don't mind introducing a dependency, use Guava's Joiner instead of StringBuffer:
Joiner j = Joiner.on("").skipNulls();
StringBuilder sb = new StringBuilder();
j.appendTo(sb, fct1());
j.appendTo(sb, fct2());
j.appendTo(sb, fct3());
String result = sb.toString();

// or even just
Joiner j = Joiner.on("").skipNulls();
String result = j.join(fct1(), fct2(), fct3());

N.B. In general, unless you need StringBuffer's thread safety, you should use StringBuilder instead. Same API, better performance.
Answer: There is nothing whatsoever you can do to make this solution simpler except shortening the method name. (There might be a solution using aspect-oriented programming, but on the whole I don't really consider that simpler.)
Answer: Unfortunately your solution with testNullity() is the best you can get with Java (consider better naming though). In fact, there is already a method that does that: StringUtils.html#defaultString.
Answer: You can create your own wrapper around StringBuffer:
class MyStringBuffer {
    StringBuffer _sb = new StringBuffer();
    public boolean append(String s) {
        _sb.append(s==null ? "" : s);
        return s == null;
    }
    public String toString() { return _sb.toString(); }
}

Answer: There is no such function in the standard API, though some methods (which do other things) have it built in.
For example, System.getProperty() has a variant which takes a default value, and if it can't find the given property, it will not return null, but the given default value. You might think of providing your fct* methods with such a "default" argument, if it makes sence.
I think C# has a ?? operator which does about what you want (you would call sb.append(fct2() ?? "")), but I suppose Java will not add any new operators soon.
A better variant of your checking function would be this:
public void appendIfNotNull(StringBuffer sb, String s) {
    if(s != null) {
       sb.append(s);
    }
}

This avoids the superfluous append call with an empty string if there is nothing to append.


Machine Learning Book (Python)

Question: I'm in search of a good book about Machine Learning.
Requirements:

Good theoretical depth (while being a ML beginner, I hold a degree in mathematics), but accompained with good examples and plenty of practical stuff.
Python as language for presenting examples, with R as a second option.
Not outdated. In some other ML book advices on stackoverflow, many suggest "programming collective intelligence", but it seems a bit old (2012).
Comment: You may want to look at [these](http://stats.stackexchange.com/q/12386/7290), although they aren't necessarily Python-specific.
Comment: You can find some, in these links:

https://github.com/josephmisiti/awesome-machine-learning - Awesome ML on github.

http://datasciencemasters.org/ - Open source data science masters.

Both of them are super sets to what you need, but you might very well like to have a look at them.
As these don't answer the question, I am them in a comment.
Answer: As mentioned in the page linked to by gung, the Elements of Statistical Learning is a great, in-depth reference. An Introduction to Statistical Learning is a more approachable book that covers many of the same topics and also provides examples in R.
I have also found Applied Predictive Modeling to be a really good, practical machine learning reference that has examples in R.
A recent Machine Learning book for Python is Building Machine Learning Systems with Python. I haven't used it yet, but it seems to provide a pretty good intro to machine learning.
Lastly, the scikit-learn Examples page provides many good examples if you already have an idea of the theory behind what you're trying to do.
Answer: I would recommend that you get two books:

General reference
I can definitely recommend Pattern Recognition and Machine Learning by Christopher Bishop. It is a bit older (2006) but you will obtain the foundation to dive in state of the art research papers.
The already mentioned Elements of Statistical Learning is also a good starting point. Especially as you can download it for free.
Python / Programming
It would be good to know whether you have previous programming experience in a scripting language (Python, R, Matlab). It is quite hard to find a book that provides both an adequate technical level and good programming examples.
If you don't have prior knowledge in "statistical programming" I would recommend a book such as Python for Data Analysis by Wes McKinney. My experience has shown that data analysis beginner have more problems with the data itself (formatting, merging) than with algorithms as there are normally toolboxes with already implemented algorithms.
Answer: Murphy's "Machine Learning" is a good book with many examples. They use MATLAB as a programming language, which means most of it can be easily run using Octave or translated to Python.
Answer: A very recent book is Data Science from Scratch by Grus, which covers "k-nearest Neighbors, Naive Bayes, linear and logistic regression, decision trees, neural networks, and clustering." I haven't read it myself, but I have heard good things.
Answer: A Course in Machine Learning by Hal Daumé III
(227 pages, 2013-2017)
aims to build intuition, with a nice blend of narrative, diagrams, equations and pseudocode (not python); the lively teacher comes through.
One can download the
whole book pdf,
or individual chapters:
Decision Trees
Limits of Learning
Geometry and Nearest Neighbors
The Perceptron
Practical Issues
Beyond Binary Classification
Linear Models
Bias and Fairness
Probabilistic Modeling
Neural Networks
Kernel Methods
Learning Theory
Ensemble Methods
Efficient Learning
Unsupervised Learning
Expectation Maximization
Structured Prediction
Imitation Learning
Answer: In my experience I recommend the book Practical Econometrics with Python. I love this book because links theory with real examples in Python. It goes from basic topics like OLS to advanced topics like VARMA.
Comment: An econometrics text that goes beyond OLS to include VARMA doesn't sound like a *machine learning* book to me.
Comment: @gung-ReinstateMonica econometrics gives you the statistical base to developed machine learning models. Also econometrics can be considered part of machine learning and sirve to introduce you to the methodology of how to develop a well specified model.
Comment: I'm familiar w/ econometrics.  I'm also familiar with machine learning.  I think it's safe to say very few people have ever started with econometrics as a basis for moving into machine learning.

Machine Learning Book (Python)


Number of ways of selecting 4 numbers.

Question:
Number of ways of selecting 4 numbers from the set of first 20 Natural numbers, such that they are in A.P.

Umm, I did try solving it but couldn't come up with something concrete. I really don't want to evaluate each case separately, that'd be really cumbersome and not-so-smart way doing it, IMO.
Answer: To get an arithmetic progression, of the form $a,a+d,a+2d,a+3d$, we need to choose $a$ and $d$, where $d \neq 0$.
If $a=1$, we need $3d \leq 19 \implies d \leq 6$. Hence, there are $6$ options.
In general, for a fixed $a$, $d$ has $\left \lfloor\dfrac{20-a}3 \right \rfloor$ options. Now sum up over all options to get the answer.

Hence, the number of ways is $$\sum_{a=1}^{17} \left \lfloor\dfrac{20-a}3 \right \rfloor = 57$$If you allow $d$ to be zero as well i.e. if you consider $a,a,a,a$ to be an arithmetic progression as well, then $$\sum_{a=1}^{17} \left \lfloor\dfrac{20-a}3 \right\rfloor  +20= 77$$
Answer: Hint: To pick four numbers in arithmetic progression, you really only need to pick the first and last number so that their difference is divisible by 3. That entirely determines the arithmetic sequence.

Number of ways of selecting 4 numbers.


How to keep only the doube quote part in a string in Javascript?

Question: I want to keep only the double quote part of a string in javascript. Suppose this is my string:
const str = 'This is an "example" of js.'
I want my result like that:
output = example
Means I want to keep only the example part which is in the double quote.
I can remove the double quote from string but I haven't found any good way to keep only the double quote part of a string.
Comment: That is not a valid string. Either escape the double quotes or using single quotes within the double quotes.
Comment: please make an attempt before asking, if you've made an attempt please provide a [mcve]
Comment: first convert this into valid string, after that you will able to apply action. ex: `const str = 'This is an "example" of js.'`
Comment: You can actually escape the double quotes by placing a \ in front of it. Here's how that would look. const str = "This is an \"example\" of js."
Answer: Get the start and last index of " and then use slice.

const str = 'This is an "example" of js';

const startIdx = str.indexOf('"');
const lastIdx = str.lastIndexOf('"');

const output = str.slice(startIdx+1, lastIdx);
console.log(output);
Answer: you could use a regex capturing group like so:
const captured = str.match(/\"(.*)\"/)
but you'll need to declare the string with single quotes and then double quotes inside like this:
const str = 'This is an "example" of js.'
try it here: https://regexr.com/4hfh3
Answer: As noted in the comments, this is not a valid string, you need to escape inner double quotes const str = "This is an \"example\" of js."
After that you can extract the value inside the quotes with a regex:
const matches = str.match(/"(.*?)"/);
  return matches ? matches[1] : str;