Is there a way to "broaden" True values of a vector in R?

Question: I have a vector of logical values among which only a few are True, and I would like to transform this vector so the two values on each side of a TRUE would become TRUE too.
So in other word I would like to transform a vector like that:
...FALSE FALSE FALSE TRUE FALSE FALSE FALSE...
so the two FALSE around each TRUE value become TRUE too, so that the final vector looks like:
...FALSE TRUE TRUE TRUE TRUE TRUE FALSE...
Here is a real example of what I'd like to change:
[20] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE  TRUE
[39] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE FALSE
[58] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE
[77] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE
[96]  TRUE  TRUE

Comment: something like `x[c(which(x) - 1, which(x) + 1)] <- TRUE`
Answer: You could do it like mentioned in the comment, but as I understand you want two values around the TRUE value to be also converted to TRUE. So you simply could do it twice.
My suggestion would be operating with the lag and lead versions of the vector and an or operation:
v = c(
    F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, F, T,
    F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, T, F, F,
    F, F, F, F, F, F, F, T, T, F, F, F, F, T, T, T, T, F, F,
    F, F, F, F, F, T, T, F, F, F, F, F, F, F, F, F, F, T, T,
    T, T
)

l = length(v)

v = v | c(v[-1], F) | c(F, v[-l])
v = v | c(v[-1], F) | c(F, v[-l])

Answer: examp <- replace(rep(FALSE, 10), c(3, 8), TRUE)
examp
# [1] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE

Base R:
replace(examp, c(outer(c(1, -1), which(examp), '+')), TRUE)
# [1] FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE FALSE

Using data.table::shift:
Reduce('|', data.table::shift(examp, -1:1, fill = FALSE))
# [1] FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE FALSE


Will damaged thumb joint hinder my ability to learn piano?

Question: A joint in my left thumb (the one closer to the palm; a.k.a metacarpophalangeal [MCP] joint) won't bend more than ~35 degrees. Will this somehow influence my piano learning?
Answer: You will have to make some adjustments, but don't let that stop you. Remember famous percussionist Evelyn Glennie is deaf.
Check out this one armed bass player. He plays all notes by hammering-on or pulling-off with his left hand. The only modification to his instrument is a handkerchief round the nut to damp the open strings.

Answer: There have been recorded jazz pianists who only used two or three fingers to improvise with, so the answer is: no, not really. you can always compensate with your other fingers.
Answer: In general, you won't need that particular joint.
The main joint involved in thumb movement at the piano  is the one at the bass of your thumb, close to your wrist -- the carpometacarpal (CMC) joint. This joint drives both vertical and lateral movements of the thumb relative to the keyboard.
Given the limitation you describe, the technique where you would most likely encounter some impingement is in performing a "thumb turn", in which the thumb passes under the other fingers (or the fingers pass over the thumb). However, as long as you keep the thumb motion primarily in the CMC joint, you should be okay.
On the other hand, being able to extend your thumb (i.e., open your hand wide) is of especial value in piano playing. So a limited inward bend at the MCP joint will be of less consequence that a limited straightening of the joint.
Answer: This depends on you. I don't know how we could give you a "yes" or "no" answer over the Internet!
The only way to answer that question is to try to learn piano. Perhaps you can learn to compensate for the restricted motion.
Look for a sympathetic piano teacher who is willing to help you work with this restriction.
If it does not work, try a different instrument.
Answer: It sure will influence your piano playing.  Every part of anatomy does.  What this most likely will result in is that you have to take fingerings in a score (in particular standard scale exercises) with more of a grain of salt than most others, and that there will be the occasional stuff that will be hard to play unchanged.
The range of affected music would still be less than if you, say, chose to play accordion instead (which does not really make use of the left thumb).  If you want to get closer to playing typical piano music with that kind of instrument, you probably want to take a converter instrument (allowing for the left hand to be playing single notes) and it makes sense learning chromatic button accordion since then you are able to play with more consistent voicings (passing a voice between left and right hand as it is often done on the piano is not possible on an accordion without audible change of character).  Also, the total accessible range in the right hand for a concert-style largest-size button accordion is 64 notes, while it is 45 for a piano accordion.  And for misappropriating piano music, range is an issue.
At any rate, the mobility of fingers can be changed quite a bit with training.  If your thumb is restricted as described, one may suspect that even within its accessible range of motion, it might have restricted dexterity.  So it's basically your own judgment call whether you think the total of your thumb to be problematic to a degree where you prefer to use an instrument that either does not use the thumb, or uses it in a very limited fashion (wind instruments tend not to require moving thumbs as much as opening and closing them mostly in-place, or even just using them for holding the instrument).
Answer: I wouldn't have said so.  You could always compensate anyway.
My left thumb is kept relatively straight at most times so the 1st joint from the tip is barely utilised.
The position where the left thumb needs to be largely dictates the position of the rest of my hand.
When my left thumb presses a key, it seems to make its up-down action with the palm relatively still, using the hidden joint at the base of the wrist, 3rd in from the tip of the thumb, rather than the joint 2nd in from the tip, which I think is the joint you're asking about.


How do I configure storage class on an existing k0s cluster

Question: When I run kos kubectl get storageclass I notice it is not provisioned and I have to add it manually. I am little unsure though on the exact procedure. The [Documentation][https://docs.k0sproject.io/main/storage/] says k0s comes with OpenEBS installed. What I am unsure of is how to enable this extension in the config file.
My existing config file has this only (I assume this should be the default config file. Is this correct ?) :
spec:
  api:
    externalAddress

I have run k0s stop then amended the config file as follows:
spec:
  api:
    externalAddress
  extensions:
    storage:
      type: openebs_local_storage

After this config change I still get the same error they is no storageclass found for the cluster. Do I need to also reinstall/install k0s, am a bit unsure because the existing k0s.yaml seems to have very little config parameters as compared to the sample given in the link .
EDIT: Using Documentation I have proceeded to generate a new k0s.yaml that uses the existing default settings. Turns out it overwrites the existing k0s.yaml (given above) : I have also effected changes to the new yaml file to produce this :
apiVersion: k0s.k0sproject.io/v1beta1
kind: ClusterConfig
metadata:
  creationTimestamp: null
  name: k0s
spec:
  api:
    address: 10.XXX.XXX.XXX
    k0sApiPort: 9443
    port: 6443
    sans:
    - 10.XX.XX.XXX
    - 172.XX.XX.XXX
    - 10.XX.XX.XXX
    - 10.XX.XX.XXX
    - fe80::XXX:XXX:XXX:XXX
    - fe80::XXX:XXX:XXX:XXX
    - fe80::XXX:XXX:XXX:XXX
    - fe80::XXX:XXX:XXX:XXX
    - fe80::XXX:XXX:XXX:XXX
    - fe80::XXX:XXX:XXX:XXX
    tunneledNetworkingMode: false
  controllerManager: {}
  extensions:
    helm:
      charts: null
      repositories: null
    storage:
      create_default_storage_class: true
      type: openebs_local_storage
  images:
    calico:
      cni:
        image: docker.io/calico/cni
        version: v3.21.2
      kubecontrollers:
        image: docker.io/calico/kube-controllers

After this change I proceed to do a reinstall of the cluster (with the new config) :
k0s install controller -c /etc/k0s/k0s.yaml

but I am now getting an error :
Error: failed to install k0s service: failed to install service: Init already exists: /etc/systemd/system/k0scontroller.service

Comment: Could you please give more details on your issue to reproduce it - do you use k0s on any cloud or on bare metal?
Comment: Bare metal server Debian 10
Comment: Im following this guide https://techviewleo.com/deploy-kubernetes-cluster-on-debian-using-k0s/
Comment: @anarxz Suggestion is to do sudo systemctl restart k0scontroller . I have run this command but still k0s kubectl get storageclass returns No resources found
Answer: I was able to reproduce your issue - in order to re-install the cluster with the new configuration for OpenEBS storage, you'll need to clean up your prior set-up:

Stop the k0s service.

sudo k0s stop

Reset previous installation that was done without your customized config file:

sudo k0s reset

Re-install k0s with your new config file and with --enable-worker flag -> so that single node k0s with controller and worker functions will be installed again:

sudo k0s install controller --enable-worker -c /etc/k0s/k0s.yaml

Start the k0s service:

sudo k0s start

After a few seconds, check that two storage classes are enabled on the cluster for you to use:

sudo k0s kubectl get storageclass

The storage classes will have volumeBindingMode: WaitForFirstConsumer - meaning, that there is delay for volume binding until application pod is scheduled on the node.
Comment: noted thanks , I was still in the middle of troubleshooting , let me work on that


How to pass the context from a view and access the context data in javascript in Django?

Question: I am passing some data in a dictionary in django view and I want to access the dictionary data in my javascript code to display the data in my html. But whenever I print the passed context, it just prints 'success' on my console and not the actual data.
Here is my dictionary structure:
context['search_successful'] = "some string"
I am passing this dictionary to my success function after making an ajax call to the view. For the time being I am just passing the HTTPResponse('true', context).
After collecting the data in my javascript code, I just want to print the data of my context which will give 'some string' on my console but it gives success everytime.
Here is my view:
def daily_object_search(request):
    context = {'search_successful': "No"}
    if request.method == 'POST':
        object_name = request.POST['search_object_name']
        print("The query for search :", object_name)
        if len(object_name) <= 2:
            print("The length of the object name :", len(object_name))
            return HttpResponse('invalid_query')
        my_cursor = mydb.cursor()
        sql = "select * from education_fruits where tag = '" + object_name + "'"
        my_cursor.execute(sql)
        result = my_cursor.fetchall()
        print(result)
        if my_cursor.rowcount <= 0:
            print("No object found")
            return HttpResponse('false')
        context['search_successful'] = "Yess"
    return HttpResponse('true', context)

Here is my template:

The console should give me something like 'search_successful : Yes' or 'search_successful : No' but gives me success everytime. Please help! Thanks in advance.
Answer: The context dictionary can be pass to render (https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/#render), I cannot find a reference to context in HTTPResponse in the doc https://docs.djangoproject.com/en/2.1/ref/request-response/#httpresponse-objects
If you want return a complex value return a json as content in the response.
You are setting the content always as true (harcoded) so in fact doesn't distinguish any case, that be unuseful in my opinion.
I suggest you to use status code to differentiate the various situations, like invalid_query, that seems a 400 Bad Request, or No object found, i.e. 404 Not Found. In this case you should use the error handler in you ajax call to capture this negative response.
If you like to stay with the success handler only, you can use a json like this:
{
'result': 'invalid_query'
}

so in the case you will want to pass the fetched elements, you can add a key in the json


Uncertainty consistency?

Question:
The problem statement, all variables and given/known data

I am given a set of x and y values x: (1,2,3,etc.) y: (1.2,2.2,3.1,etc.) with a given uncertainty and am asked
a) find the best fit
b) at what prob can you rule out a 5% higher slope
c) is the stated uncertainty consistent with the data?
I can find the best fit relatively easily by minimizing chi-sqd and setting the derivatives to 0. I am confident in my result as it matches with the graph given by excel.
For part 2 I tried putting a higher value for the given slope into the chi-sqd equation and checking a chart but that didn't give me a reasonable answer (not completely sure about the degree of freedom)
I am not sure how to approach the third part. I have computed the errors in the fitting coefficients but that doesn't seem to play into it.
Thanks,
Comment: Because this is a homework/self-study question, you should add the `self-study` tag to your question. See http://stats.stackexchange.com/tags/self-study/info
Comment: Sure thing, my mistake
Answer: Without more context is difficult to be sure.  There are many models that could be fit, and many criteria used to fit those models.
Part (b) suggests that the model is linear ("slope") which suggests that the criterion is Least Squares.
Part (c) reinforces the hint that Least Squares is the criterion, because the MS Residual estimates the uncertainty from the data.  This could be used for a $\chi^2$ test of the uncertainty (with $n-2$ df).
Comment: Yes a linear model fits the data set, the slope is around 1 and the y-intercept is 0. Not sure what other context to give?

I put a value of a 5% higher slope into the chi-sqd equation and got a number like 90, which is untenable.
Comment: Why are you using $\chi^2$?  I'm at a bit of a loss to figure out how you are supposed to test the hypothesis $\beta > 1.05\, \hatP\{\beta}$  This is a data-dependent hypothesis, and so isn't covered by Neyman-Pearson theory that I am aware of.  If you let $\sigma_=o$ be the specified variance (uncertainty), then $\frac{SSRes}{\sigma_o^2} \sim \chi^2_{n-2}$ when $H_o:\sigma = \sigma_o$.
Answer: Probably, in the 5% slope it is asking what is the probability to have a slope that is 5% higher than the estimated one.
For example, let us assume that you have a slope of 1.00, then what is the probability to have a a slope that is 1.05 or above?
You can estimate using the Standard Error for the slope .When you do a regression the software should provide you the Standard Error for the slope.
For example, let us assume  Standard Error to be 0.003,  you could reframe the question in :
What is the probability for a Normal Distribution with mean 1.00 and standard deviation 0.003 to have a slope of 1.05 or higher.
If this probability is very low  then you can say that 1.05 is not consistent with the data

Uncertainty consistency?


Closure of an open set

Question: Given an open set $A$ as a proper subset of an open set $B$, is the closure of $A$ necessarily contained in $B$.  I think it is, but would like a proof either way

Context of the question as given in the OP's answer:
The reason I asked the question in the first place was that I was trying to prove what I call the Russian Doll theorem to my satisfaction.   Given $X$ a normal topological space $A$, a closed subset of $X, U$ the open set containing $A$ which normality guarantees.  Prove that $U$ contains another open set (call it $W$) whose closure is contained in $U$.
I started with $X - U$ as another closed set and was able to prove to my satis faction that normality guaranteed the existence of $V$ another open set containing $X - U$ disjoint from another open set $W$ also containing $A$ and such that $W$ was a proper open subset of $U$.  I needed to prove that the closure of $W$ was contained in $U$ and couldn't do it
Comment: Take $A,B\subset\Bbb R$ with $A=(0,1)$ and $B=(0,2)$. Then $A$ and $B$ are open, $A$ is a proper subset of $B$, the closure of $A$ is not contained in $B$ (i.e. the number $0$).
Comment: No, you can construct a counter example with just three elements, letting the open sets be those containing a specified element (plus the empty set).
Comment: Even though the title "Closure of an open set [closed]" is amazing, I think this question should be reopened as it is self-contained and includes all the context it needs.
Comment: I don't think the context given in the answer is really needed anyway. Anyone who knows even the very basics of topology knows what an open set and a closure are, so why complicate the question with any more information than it originally contained?
Answer: No : take $A={]{-1},0[}$ and $B={]{-\infty},{0}[}$.
Comment: Any reason you took the negative line? Lol
Comment: I guess my mind saw the closure from the left side to the right side :)
Comment: Thanks was trying to prove what I call the Russian Doll theorem to my satisfaction.
Answer: I will prove that the only topology that satisfies the given property is the discrete topology.
Assume that $(X,T)$ is a topological space such that if $A$ and $B$ are open sets with $A$ a proper subset of $B$, then $\bar{A}\subseteq B$. Let $E$ be any subset of $X$, and consider the boundary of $E$,
$$\partial E=\bar{E}\setminus E^{\mathrm{o}}$$
If $x\in E^{\mathrm{o}}$, then by assumption $x\in\bar{E}$, so $\partial E=\emptyset$. Note that $E$ is closed if and only if $\partial E \subseteq E$. Therefore $E$ is closed. Since $E$ was an arbitrary set, it follows that $T$ is the discrete topology on $X$.

Closure of an open set


Counting Cells Formula with Criteria: Date & String & Empty Cells

Question: I'm trying to do a whole lot of counting using a table (growing) with over 4,000 entries by date. The table in the picture below is the one I am trying to fill in. I Have a few simple criteria, but I'm not sure how to do this in a formula within a cell that I can copy across this giant table. I've tried multiple CountIf and CountIfs with no luck.
The criteria are as follows: I want to count the number of times a tool occurs (column E) in a particular date (Column A). Only counting when Column W is not empty. Then I want to copy that through this entire table checking every tool by every date.

The data is coming from this table:
Comment: Wouldn't a pivot table be able to do this without any formulas?
Comment: I actually don't have much experience in pivot tables. I'll have to look into that.
Comment: If not using the formula from @ScottCraner , then this may be a perfect reason to start using them / get more knowledge about them. They offer a LOT of cool stuff without using any formulas
Answer: COUNTIFS(),  With your date lookups including a time portion we need to bracket the  days.
<code>=COUNTIFS('Sheet1'!$A:$A,">=" & INT($C3),'Sheet1'!$A:$A,"<" & INT($C3)+1,'Sheet1'!$E:$E,D$1,'Sheet1'!$W:$W,"<>")
</code>
Change Sheet1 to the sheet name in which the data is located.
Put this in D2 and copy over and down the grid.
Comment: So for some reason or another while I thought this was the solution, it's having an issue. if I filter my data by a particular date 7/2, and by one particular tool, there are being listed one more tool than there should be, furthermore it's not omitting the blank spaces for some reason.
Comment: I'm going to spend some time looking at this and let you know if I can find the issue
Comment: I found the referencing was off a touch to the wrong cell from D2. Fixing and i'll let you know
Comment: Okay, so changing the referenced cell worked and now the numbers are all accurate for total lines, but it's not omitting the rows with blank cells. I'll look further into this.
Comment: make sure those cells are truly blank, no spaces or other non printable characters.  @CodingNovice
Comment: Or if the values are returned by formula, that the return is not `" "` which has a space in it.  This is looking for a truly blank cell or a formula that returns `""` without the space. @CodingNovice
Comment: The strangest thing is that the cell showed nothing in it. WHen i clicked to edit it it still showed nothing in it (not even spaces). When I simply hit delete on the cell it finally worked.


Prove that: $(AV)^⊥ = (A^T)^{−1}(V^⊥).$

Question: Let $A \in R^{n×n}$ and V be a subspace of $\mathbb{R}^n$. I have to prove that:
$(AV)^⊥ = (A^T)^{−1}(V^⊥).$
From the lectures I know that we have that the orthogonal complement is gyven by:
$V^⊥$ = ${y \in \mathbb{R}^n | y^Tx = 0 \space \forall x \in V}$ and that we have $(V^⊥)^⊥ = V$.
Any help would be fine. Thanks in advance.
Answer: Let $x\in (AV)^\perp$, it means $x^TAv=0$ for all $v\in V$, that is,
$$(A^Tx)^Tv=0\ \text{ for all }v\in V$$
so that $A^Tx\in V^\perp$, hence $x\in (A^T)^{-1}(V^\perp)$.
The converse follows similarly.
Comment: Thank you very much!
Comment: Do I have to prove the converse? Or isn't that necessary?

Prove that: $(AV)^⊥ = (A^T)^{−1}(V^⊥).$


Do overlapping left and right coset spaces have a name?

Question: I have been studying they symmetries of the square, D₄. I would like to use the subgroups that are not normal to make a coset space, but since they are not normal, the right coset space is different than the left coset space. However, I did notice that the left and right coset space of pairs of subgroups in the same conjugacy classes overlap. Is there a name for this whole system?
This picture is one of the two conjugacy systems. There are four overlapping coset spaces in the form of the two rows and columns.
Comment: I assume $r$ stands for rotate and $f$ stands for flip and $e$ the identity. Those are not double cosets; I'm not sure they have a name, but it seems as if they ought to.
Answer: Contrary to the comment, these are double cosets.  They are not all of the double cosets. They are simply the double cosets that are also cosets.  Usually double cosets, being unions of cosets, are larger than cosets, but when the a left coset $H_1g$ of $H_1$ coincides with a right coset $gH_2$ of $H_2$, then $H_1gH_2$ coincides with both of them.  This happens precisely when $H_1$ and $H_2$ are conjugate, and the number of such cosets is $[G:H_1]/|Orb| = [N_G(H_1):H_1] = [N_G(H_2):H_2]$, where $|Orb|$ is size of the orbit of $H_1$ under conjugation.
In this case $[N_G(H_1):H_1]=2$ since $N_G(H_1)$ is generated by $H_1$ and the center (the 180 degree rotation), so there are two coset-sized double cosets in $H_1\backslash G/H_2$ and similarly for $H_2\backslash G/H_!$.  In each case the other double coset has the other $4$ elements of $G$, for a total of $3$ double cosets in each case.
Specifically, if I am able to read your picture properly (the fonts in it are a bit blurry), $H_1\backslash G/H_2$ consists of the double cosets $H_1eH_2=\{e,rf,rr,rrrf\}$, $H_1rH_2=\{r,rrf\}$, and $H_1fH_2=\{f,rrr\}$.  Note that the double cosets with two elements are precisely the sets that are simultaneously left cosets of $H_2$ and right cosets of $H_1$.
I'll leave $H_2\backslash G/H_1$ as an exercise so you can validate your understanding.
Comment: I've added those details.
Comment: I'm a little confused due to the contradictory statements that this is and is not a double coset. Is this entire system a single double coset space, or are many double cosets spaces that link together with coset spaces to make this? Would you mind writing out the elements of one double coset space so I can know exactly what you are referring to?
Comment: oh, I see! Let me know if this is correct. The second set of double cosets are $H_2eH_1=\{e,rf,rr,rrrf\}$, $H_2rH_1=\{rrr,rrf\}$, and $H_2fH_1=\{r,f\}$.
Comment: Yes, that's right.
Comment: And for fun you can even try $H_1\backslash G/H_1$


Editing border of one side in a cell without CSS, only with HTML/XHTML?

Question: Say I have a table that looks like this: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_table_collapse
Is it possible to remove/edit cells of a border without CSS, and only using HTML/XHTML?
For example, in '50', can I remove the right border of that row only?
Comment: Why one should want to do that?
Comment: Without CSS you can't.
Comment: This is for a little project I'm working on without using CSS, and I came across a problem where it wasn't possible to edit the cells to have specific borders.
Answer: This answer revolves around section 11.3.1 of the HTML401 specification; this uses data which isn't present in the HTML5 specification.
HTML offers some support for borders through the frame and rules attributes. These affect entire columns or rows, but not individual cells. You cannot use these to apply a border to only one cell, but you can use this to apply a border to a row or column.
For example, setting frame="rhs" (right hand side) and rules="all" on the table element will render the border like this (JSFiddle demo):
1      | 2      | 3      |
       |        |        |

Values the frame attribute supports:
void: No sides. This is the default value.
above: The top side only.
below: The bottom side only.
hsides: The top and bottom sides only.
vsides: The right and left sides only.
lhs: The left-hand side only.
rhs: The right-hand side only.
box: All four sides.
border: All four sides.

Values the rules attribute supports:
none: No rules. This is the default value.
groups: Rules will appear between row groups...
rows: Rules will appear between rows only.
cols: Rules will appear between columns only.
all: Rules will appear between all rows and columns.


Yaml Object Lists

Question: I want to deserialize a list of objects with yaml.dotnet
You can see my YAML and source code below.
I get the Error that lesson is not part of my lesson object. So for any reason the compiler is expecting that "Lesson" is a property on the class
Code:
var deserializer = new Deserializer();
var items = deserializer.Deserialize<List<YamlLesson>>(yaml);

YAML:
Lessons:
  - ShortKey: "M/A/L"
    Type: Static
    Items: ["M","A","M","L"]
  - ShortKey: "der/die/datas"
    Type: "random"
    Items: ["der","die","das"]

Class to which the yaml should be mapped
 public sealed class YamlLesson
    {
        public string ShortKey { get; set; }

        public string Type { get; set; }

        public List<string> Items { get; set; }
    }
}

Exception:

YamlDotNet.Core.YamlException: '(Line: 1, Col: 1, Idx: 0) - (Line: 1,
  Col: 1, Idx: 0): Expected 'SequenceStart', got 'MappingStart' (at
  Line: 1, Col: 1, Idx: 0).'
Answer: Well, the error is that you tell YamlDotNet that you want to deserialize into a List<YamlLesson>, so YamlDotNet expects the root element of your YAML to be a sequence. However, your YAML's root element is a mapping: It has one key, Lessons, and the corresponding value, a sequence of lessons.
This YAML could be properly deserialized into this class:
public class Root {
  public List<YamlLesson> Lessons { get; set; };
}

However, if you want to deserialize directly to the List, just drop the root mapping and change your YAML to be
- ShortKey: "M/A/L"
  Type: Static
  Items: ["M","A","M","L"]
- ShortKey: "der/die/datas"
  Type: "random"
  Items: ["der","die","das"]

Yaml Object Lists


Django Postgres Case Insensitive Textfield and citext

Question: for my Django app i use PostgreSQL (9.3) and i want to use case insensitive text in my database. For this Popstgres has a 'new' extension named 'citext'.
As i understand it, django can't use this extension out of the box, so i have made an custom field:
class RsCharField(models.CharField):
    ...
    def db_type(self, connection):
        return 'citext'

I use a CharField as baseclass, because i still want all the django perks of being able to set a maximum length and the validators that come with that.
The database is created correctly and i end up with citext-tables:
 description       | citext                   | not null

But when i do a query, django translates te query to:
SELECT * FROM .... WHERE mytable.description::text LIKE 'TEST%'

which still is case sensitive. When i do a manual select and drop the ::text it works case-insensitive.
Question: What am i doing wrong, and how can i make my CharFields behave like case-insensitive fields in django when doing queries?
note: most importantly i want my indexes to behave like case insensitive indexes.
Comment: Can you share your queryset filter?
Answer: use the classes provided in django.contrib.postgres.fields.citext
https://docs.djangoproject.com/pt-br/1.11/_modules/django/contrib/postgres/fields/citext/


Is this a bad residual plot?

Question: I Have the below residual plot as result of a multiple linear regression I have fitted.
I do not know how to interpret the results. Is it showing heteroscedasticity? There are only about 48 observations in the table and one of the predictor variables is categorical(1 and 0).
Comment: I think it is good. But there is no objective approach about this topic. so it is possible that others think it is not good.
Answer: Heteroscedasticity is when the variance of one variable is unequal across the range of another variable you are using to predict the first. Essentially, in the above residual v.s. fitted values plot you would expect to observe a trumpet shape. I don't personally see any.
There are tests to determine if your data follows the "equality of variance" assumption - like the levene's test - however, these can be overly sensitive, so most people like to do it by eye. There is the small hint at curvature in your residuals, suggesting that there is still some pattern left to explain in your data, which could potentially be solved by log transforming your response variable or by fitting a quadratic term to one of your covariates. If you added a pairwise matrix of each variable plotted against the others, such as one generated from pairs(df), then I might be able to give you more help.

Is this a bad residual plot?


Vue apollo - send authorization over websockets

Question: I have a vue web app from which I'm trying to run a subscription using a hasura query.
My problem is that I cannot pass to the Websocket request an authorization token as the backend expects.
These are my current settings:
const token = localStorage.getItem("token") || null;

const options = {
  httpUri: //graphql http endpoint,
  wsUri: //graphql ws endpoint
};
let link = new HttpLink({
  uri: options.httpUri
});

// Create the subscription websocket link if available
if (options.wsUri) {
  const wsLink = new WebSocketLink(
    new SubscriptionClient(options.wsUri, {
      lazy: true,
      reconnect: true,
      connectionParams: {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    })
  );

  // using the ability to split links, you can send data to each link
  // depending on what kind of operation is being sent
  link = split(
    // split based on operation type
    ({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === "OperationDefinition" &&
        definition.operation === "subscription"
      );
    },
    wsLink,
    link
  );
}

const authLink = setContext((_, { headers }) => {
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : ""
    }
  };
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message }) => {
      if (message.includes("unauthorized")) {
        EventBus.$emit("unauthorized");
      }
    });

  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const apolloClient = new ApolloClient({
  link: ApolloLink.from([errorLink, authLink, link]),
  cache: new InMemoryCache(),
  connectToDevTools: true
});

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
});

When I try to run the subscription I get

HTTP Authentication failed; no valid credentials available

And in the ws request header I cannot see my Authorization bearer set.
A side info I need authorization for both http and ws requests
Answer: I think errorLink or authLink unexpectedly change websocket header token. You try modifying a bit:

    const httpLink = from([
      authLink,
      // errorLink,
      new HttpLink({
        uri: Config.httpDataHost,
        headers: {
          [XHasuraClientName]: Config.hasuraClientName
        }
      })
    ]);

    const wsLink = new WebSocketLink({ ... });
    const link = ...
    const apolloClient = new ApolloClient({
      link: ApolloLink.from([errorLink, link]),
      cache: new InMemoryCache(),
      connectToDevTools: true
    });

If it doesn't work, you can try commenting errorLink to check. Another thing is, you shouldn't get token globally, but use lazy function so ApolloClient can always get latest access token from local storage

const getIdToken = () => localStorage.getItem('token') || null;

const wsLink = new WebSocketLink({
  uri: options.wsUri,
  options: {
    connectionParams: () => ({
      headers: {
        Authorization: getIdToken(),
      }
    }),
    ...
  }
});

PS: I have an example repository with React + Apollo Client 3.0. Although you are using Vue.js,Apollo Client construction is the same https://github.com/hgiasac/ra-hasura-typescript-boilerplate/blob/auth-jwt/src/shared/ApolloClient.ts
Comment: I tried commenting the `erroLink` ,  but still no headers sent to the ws request, the `connectionParams` function is never called
Comment: do you run subscription after authentication? Subscription won't run until first subscription call with `lazy` option
Comment: Yes, I found the problem - I am using the hasura engine inside docker, and nginx as reverse proxy to that hasura instance, so I had to create a route in nginx config file to point to the inner docker hasura engine, but your github example really helped, thanks a lot for this


Como usar BETWEEN e o LIKE juntos numa Query?

Question: Bom tenho uma tabela que contém algumas tabelas sendo elas ( DATA_INICIAL , DATA_FINAL ) , contudo estou tentando gerar um relatório que contenham os dados entre as datas iniciais e finais , sendo que quem coloca essas informações é o usuário ( Não é algo definido ) .
A minha busca no banco hoje só tira os dados do dia inicial e do dia final contudo quero todos os dias dentro desse intervalo , como posso realizar isso ?
Minha Consulta :
SQL SERVER : SELECT * FROM dbo.NOME_DA_TABELA WHERE DT_INICIAL LIKE '$data_incio' AND  DT_FINAL LIKE '$data_final'

$data_inicio E $data_final são as variáveis que os usuários vão colocar num form que eu envio para essa pagina .
Comment: Você quer que os registros selecionados tenham ambas as datas DT_INICIAL e DT_FINAL entre as datas inicial e final fornecidas ou basta uma delas estar dentro do período fornecido? Creio que basta utilizar BETWEEN não entendi este LIKE.
Comment: Creio que vc quis dizer 'tabela que contám algumas colunas'. DATA_INICIAL e DATA_FINAL são de que tipo? Se você rodou e não de erro com o ilike creio que sejam varchar, nesse caso é preciso converter para data e usar o between comentado acima. coloque a ddl da tabela na pergunta.
Answer: Você pode filtrar por registros com a data inicial igual ou maior que a informada e com a data final menor ou igual do que a selecionada pelo usuário. A consulta ficaria da seguinte forma:
SELECT * FROM dbo.NOME_DA_TABELA WHERE (DT_INICIAL >= '$data_incio' AND  DT_FINAL <= '$data_final')

Answer: Você precisa de um BETWEEN:
SELECT *
  FROM dbo.nome_da_tabela
 WHERE dt_inicial BETWEEN '$data_incio' AND '$data_final'

BETWEEN
Especifica um intervalo a ser testado.
Sintaxe
test_expression [ NOT ] BETWEEN begin_expression AND end_expression


I want the view to show no results when the filter doesn't containing anything

Question: I am trying to use the Views module for an auto-submit field, to get the names from my taxonomies. How can I get the field to show the results after the users type something into the input box, instead of showing all the results when nothing has been entered as value for the filter?
I have tried a number of contextual filters but no luck.
This what the current search looks like, if I type in one of the terms or the field name it matches up to what I type which is how i wanted it to work, the problem is the the results are showing by default before I type anything.
Comment: do you mean an auto-complete field?
Comment: no i mean no results until the person starts typing in the letters to match the taxonomies, pretty much exactly like how this search is http://www.google.com/finance?tab=we when you type in goog it starts matching the company name
Comment: Are you looking for how to solve it using an existing module, or are you happy also with understanding how to solve this with your own module?
Comment: Either way is preferred I just want to solve it lol
Answer: This is built into views 3:

Edit your view
Set Advanced | Exposed Form | Exposed Form Style to input required
Comment: Whoo hoo! this is the right answer. The other answer is fraught with difficulties and work-arounds, this one is the correct, clean way to do things IMO.
Comment: I agree, this is the correct answer.
Comment: This is THE ANSWER!!!
Answer: If you set the exposed filter to "Required" with nothing in the default 'Value' box, then the view shows nothing until a user fills in and uses it.
Tip: If you find that your exposed filter doesn't show up when it is empty, then (after checking 'Use AJAX' is selected if it's a block) add something to the view's "No results behavior" field on the right, such as a Global: Text area containing a space or  .

Another option is setting a default value that doesn't match anything - for example, if the default value is a friendly message like "Enter team name here" or "Search teams", or something neutral like "0" or "–––", there will be no matches until they enter their input, so the view will be blank until they enter input. This does mean there will be one unneccessary extra query on the page - but this should usually be cached.
If you use the default, for improved usability, you can do what the "Search finance" text in the Google page you link to does, and save your users the inconvenience of deleting that default entry themselves with some jquery code that clears the field when it gains focus, and for even better usability, you can style the default text to be lightly greyed out, then remove this style when the field gains focus.
There are lots of guides out there on how to do this, I won't duplicate them here. Here's one example. You could drop code like that into your theme's scripts.js file (using Drupal.behaviors instead of $(document).ready so it still works when elements get updated by AJAX). There might be a way to do this in Drupal php on the server side or in configuration too, but I don't know of one off the top of my head.
You can also get the best of both options, avoiding that extra query and only showing the default "Search..." text to people who have Javascript enabled (who it won't be a nuisance to), by ticking the "Required" checkbox, leaving Value blank, and using something like $('#whatever-the-input-field-is').attr('value', 'Search teams'); in addition to code like the above to write in the friendly disappearing message on page load, only for people with javascript is enabled, without causing a query that will find nothing.

If I misunderstood your question, and it's the autocomplete feature you're asking about, then check out autocomplete_deluxe
Comment: "If you set the exposed filter to "Required" with nothing in the default 'Value' box, then the view shows nothing until a user fills in and uses it." — this what @JeremyLove needs I guess :)
Comment: I tried what you both suggested about the required field and the input field disappeared...
Comment: @JeremyLove See the last but one paragraph of my answer: "Tip: If you find that your exposed filter doesn't show up when it is empty, then (after checking 'Use AJAX' is selected if it's a block) add something to the view's "No results behavior" field on the right, such as a Global: Text area containing a space or ` ` "
Comment: @JeremyLove did you try adding the "No results behaviour" as suggested?
Comment: Yeah I did try that the whole view still disappeared, with your suggestions I will look into this further to see what I can figure out. Also im using view populate filters module, im wondering if that has something to do with it
Comment: Actually tried what you said before and it didnt work so I tried again and I added a label and then took it away and it worked, I dont know why... it seems a little screwy to me but thanks
Comment: Yeah I agree, I think it's probably a bug in Views that empty views which contain interactive elements that can make them non-empty aren't rendered at all by default, but realistically, I think civilisation will probably have fallen and the Internet will have become some long forgotten ancestor deity whose name is chanted around a campfire  before any patch or bug report I attempted to put into the Views queue got looked at...
Comment: Lol i'm just now seeing this. I caught a bug a while back and reported it and they got around to fixing it within a few weeks, so it is not that bad, but I will go ahead and report this to them to let them know.
Comment: Yeah I was a bit unfair, the Views guys aren't too bad, they've got a Views Bug Squad I think they call it and they've got a lot better at acting on bugs. Ctools and Panels on the other hand...


Adding a reverse proxy - nginx or varnish

Question: We currently serve most of our Rails and LAMP apps over Apache and Apache passenger, but we're considering adding Nginx or Varnish as a reverse proxy to reduce the load on our servers somewhat.
I'm aware that you can use Varnish and Nginx together, but given that there's investment of time in learning how both work, and where possible we want to keep the number of 'moving parts' in our infrastructure as low as possible, I'm trying to work out what the advantages and disadvantages are between using:

nginx by itself as a the reverse reverse proxy/cache
varnish alone as the reverse proxy/cache
nginx and varnish together

I understand nginx is known to be extremely fast, and it's gaining prominence as a full blown http server as it gets more popular, so I can see the argument for investing some time in learning how this server works, but Varnish is still an unknown to me.
Why would I use Varnish if nCache is now in Nginx?
Thanks
Answer: Do you anticipate using Edge Side Includes (ESI)?  If so, the Nginx ESI module is broken and has some open bugs.  If you use Varnish, output isn't compressed, so you're somewhat stuck using Nginx to do compression of ESI enabled pages.  While I work with Python frameworks, Rails is similar.
With your current setup, you could do something like:
Nginx -> Apache -> Passenger -> Rails
Varnish -> Apache -> Passenger -> Rails
Both would drop in front of your existing system.  With Nginx, you could also give it direct access to the static files and allow it to serve those without having to proxy through Apache.  Using the Location directive, you can slice off portions of your webspace and prevent that from having to go through the proxy.
However, if you wanted to move completely to Nginx, your infrastructure becomes:
nginx -> passenger -> rails    (nginx -> uwsgi -> python)
If you add Varnish, you end up with:
varnish -> nginx -> passenger -> rails
unless you use ESI, in which case you end up with:
nginx -> varnish -> nginx -> passenger -> rails
At some point, removing Varnish from the mix becomes quite intriguing.  However, recent Varnish releases are still faster than Nginx's caching and you have a lot of control over how you can cache.  While both Nginx and Varnish give you quite a bit of control, Varnish's VCL allows you to write C code to do things that neither does out of the box, without touching the daemon's source code.  Whether that is useful to you is up to you.
Since you are using Apache currently, I would be more inclined to put Varnish in front unless you are going to migrate to Nginx and remove Apache completely.  Varnish in your case is more of a drop-in solution.  If you decide that you're going to use ESI in the future, you would need to run both.
Comment: Thanks - as we haven't switched to nginx just yet, your answer is making varnish look like a more compelling solution in the short run.

In the long run nginx, looks to be a really capable replacement for Apache, but right now - I don't think it's too wise to make that jump for now, as we have to support a number of java and perl apps too, I'm expecting all kinds of unexpected pain in the transition...
Comment: @karmawhore would you like to update something, maybe the changes in both nginx and varnish, along these years.
Answer: Here is a comparison test of Varnish, Nginx (the raising star), Apache Traffic Server (another proxy cache), G-WAN (an application server with C scripts) and Lighttpd (a real good wweb server):
http://nbonvin.wordpress.com/2011/03/24/serving-small-static-files-which-server-to-use/
Apache Traffic Server is an HTTP proxy and cache server created by Inktomi, and distributed as a commercial product before Inktomi was acquired by Yahoo.
Yahoo says that it uses TS in to serve more than 30 Billion objects per day. They also say that TS is a "product of literally hundreds of developer-years".
Comment: Here's a comparison with the comparison: http://martijn.vanderlee.com/?p=396


django python blank=True still required

Question: In the code below, somehow the fields that have blank=True are still required and cannot be Null
Example:
# Skill train timer
    class SkillTrainingTimer(models.Model):
    """
    Character Training timer,  keep track fo what skill is in training, and when it is done
    """
    character = models.ForeignKey(Character, unique=True)
    skill = models.ForeignKey(Skill, blank=True)
    trainingground = models.ForeignKey(TrainingGround, verbose_name='Training ground')
    timer = models.DateTimeField()

and now i do:
train_skill = SkillTrainingTimer(
        character=some_character_obj,
        trainingground=some_trainingground_obj,
        timer = fatetime.datetime.now()
)
train_skill.save()

It starts complaining skill cannot be Null.  I have this in a lot of models and functions and so far i just dumped some useless data in it.
Answer: null=True sets NULL on the column in your DB.
blank=True determines whether the field will be required in forms. This includes the admin and your own custom forms. If blank=True then the field will not be required, whereas if it's False the field cannot be blank. Hope this helps!
Answer: You have to add the null=True argument on the field definition, preferably before a syncdb (or you can migrate with South)
skill = models.ForeignKey(Skill, blank=True, null=True)

Comment: Woow, this answer was made a long time ago. Reading "South" brought to me nostalgia
Answer: For a foreign key, there isn't really a valid blank value other than NULL. Effectively, on the database side, you need to either enter NULL, or some valid value for that foreign key.
So, to allow the foreign key to be entered, you also need to add null=True. This will enter blank values as NULL into the database, as specified in the documentation.
However, a simple blank=True is recommended for fields like models.String, where there is another blank value other than NULL, i.e., the empty string. This allows you to use NULL where you want to, say, differentiate a field that has never been filled, from a field that has been filled in with a blank value. The distinction is slim, and it will usually not be necessary, but it is possible to have as a requirement (although it's not recommended in the documentation).

django python blank=True still required


Set the maximum buffer size of a web socket server endpoint

Question: How do you set the maximum buffer size for a web socket server endpoint? I'm having an issue with the server closing because client is sending binary data that exceeds the Max Frame length:
[io.net.cha.DefaultChannelPipeline] (vert.x-eventloop-thread-6) An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did no
t handle the exception.: io.netty.handler.codec.http.websocketx.CorruptedWebSocketFrameException: Max frame length of 65536 has been exceeded.

I'm just using the Quarkus Websocket demo: https://quarkus.io/guides/websockets
[UPDATE]
I have tried:
@OnMessage(maxMessageSize = 1048576) // not working!
public void onMessage(ByteBuffer message, @PathParam("username") String username) {
    broadcast(message, username);
}

and
quarkus.websocket.max-frame-size=1048576
both not working.
[ANOTHER UPDATE]
Just to add, I did some more testing.
In my code I added this to check for the real max frame size set:
@ConfigProperty(name = "quarkus.websocket.max-frame-size"")
Integer maxFrameSize;

Then simply log it:
@OnMessage
public void onMessage(ByteBuffer message, @PathParam("username") String username) {
 System.out.println("Max frame size: " + maxFrameSize);
 broadcast(message, username);
}

Here's the output:
Max frame size: 1048576
2020-04-16 15:29:23,901 WARN  [io.net.cha.DefaultChannelPipeline] (vert.x-eventloop-thread-1) An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did no
t handle the exception.: io.netty.handler.codec.http.websocketx.CorruptedWebSocketFrameException: Max frame length of 65536 has been exceeded.

It seems like even the parameter is set the actual handler is still using the default one 65536
Answer: There's a property that you can specify in application.properties
quarkus.websocket.max-frame-size=65536

65536 is the default value, play around with what will work for you
Comment: @xybrek looks like you're using `ByteBuffer` instead of `String` as in guide. This causes an issue for me as well. It's not the best solution to use String, you might need to create an issue on github for this if there won't be any additional answers
Comment: Ah yes, maybe that's the reason, it might not have been part of the Quarkus developer test that missed this issue, maybe they only tested with String payload. I hope there's a work-around since waiting for the next release is quite would be out of schedule in my project case.
Comment: Can you open an issue in the Quarkus issue tracker about this. We do release roughly every months with more frequent bug fixes streams.


Define a recursive function

Question: How to Define a recursive function is-bst : EBT(N) → Bool in such a
way that is-bst(t) = true if, and only if, t is a binary search tree.
Comment: What is "EBT(N)" ?
Answer: Do you know a way
to traverse a tree?
There are more than one.
If your definition of
a binary tree
is a tree that has at most two leaves
at each node,
then
traverse the tree
and check each node
for the number of leaves.
If the number is more than two,
fail.
If all node have at most
two leaves, succeed.
Answer: Here's a possible solution
$$\operatorname{isBST}(x)=\left\{\begin{array}{ll}
\mbox{true},&x\lt0\\
\mbox{false},&\operatorname{prev}(x)\ge0\land\operatorname{value}(x)\le\operatorname{value}(\operatorname{prev}(x))\\
\mbox{false},&\operatorname{next}(x)\ge0\land\operatorname{value}(x)\ge\operatorname{value}(\operatorname{next}(x))\\
\operatorname{isBST}(\operatorname{prev}(x))\land\operatorname{isBST}(\operatorname{next}(x)),&\mbox{otherwise}
\end{array}\right.$$

Define a recursive function


Counting number of isomorphisms between graphs using its automorphism group

Question: Define $\mathcal{G}_n$ to be the set of labeled graphs whose vertices are $v_1,v_2,..,v_n$.
Let $G,H \in \mathcal{G}_n$ such that $G \cong H$ (They are isomorphic),
let $\theta$ be the isomorphism.
I need to show that the set of all isomorphisms between G to H is exactly the coset $\theta \operatorname{Aut}(G)$, where $\operatorname{Aut}(G)$ is the automorphism group of G. This is what I've done so far:
Let $\operatorname{Iso}_G ^H$ be the set of isomorphisms from $G$ to $H$, I need to prove that $\operatorname{Iso}_G ^H=\theta \operatorname{Aut}(G)$.
I've already shown that for every $\alpha \in \operatorname{Aut}(G)$, the composition $\theta \alpha$ is a isomorpishm, so $\operatorname{Iso}_G ^H \supseteq \theta \operatorname{Aut}(G)$ is immediate.
For the other direction, let $\theta_0 \in \operatorname{Iso}_G ^H$. If $\theta_0=\theta$ pick the identity permutation from $\operatorname{Aut}(G)$. (Which always contains atleast it)
Now this is the part where I'm stuck.
I know that two different isomorphisms agree on some vertices $v,u$ (meaning $\theta_0(v)=\theta(u)$) $iff$ $v$ and $u$ are similar. (There's a automorphism that maps them to each other)
So in a hand-wavy fashion - since similarity is an equivalence relation, I can always find $\alpha \in \operatorname{Aut}(G)$ that "repairs" the permutation of specific equivalence class such that $\theta$ will act will act on them in same way that $\theta_0$ does. How can I capture that intuition in more rigorous manner? Or if my intuition is wrong, how can I prove that $\operatorname{Iso}_G ^H \subseteq \theta \operatorname{Aut}(G)$?
Answer: In general, if $X$ and $Y$ are two isomorphic objects (graphs, sets, groups, etc...) and $\theta : X \to Y$ is a fixed isomorphism, then
$$
\begin{align*}
\gamma \mapsto \theta \circ \gamma:  \mathrm{Aut}(X) \to \mathrm{Isom}(X,Y) && && (*)
\end{align*}$$
is a bijection. Since compositions of isomorphisms are isomorphisms, we know in particular that $(*)$ indeed defines a mapping $\mathrm{Aut}(X) \to \mathrm{Isom}(X,Y)$.
But why is $(*)$ a bijection? Well, the point is that we can write down the inverse mapping.
$$
\begin{align*}
\gamma \mapsto \theta^{-1} \circ \gamma : \mathrm{Isom}(X,Y) \to \mathrm{Aut}(X) && && (**)
\end{align*}$$
is a map in the other direction, and you can easily check that $(*)$ followed by $(**)$ is the identity, and similarly $(**)$ followed by $(*)$ is the identity.


Estimate the remainder in Taylor's formula for a nonlinear map between Hilbert spaces

Question: I am trying to get my head around these introduction to Hilbert/Banach spaces. I kind of get the basic, but is still currently struggle to prove the following question.

Suppose $F(x)=0$ is a non-linear forward operator acting on a pair of Hilbert function spaces $F: H_1 \rightarrow H_2$ which has the following properties:
  $$
\| F'(x)\|_{\mathcal{L}(H_1, H_2)} \le N_1 \forall x \in H_1
$$
  $$
\| F'(x) - F'(y)\|_{\mathcal{L}(H_1, H_2)} \le N_2 \|x - y\| \forall x,y \in H_1
$$
  where $F'(x)$ is the Fréchet derivative. Using the Taylor's formula:
  $$
F(x+h) = F(x) + F'(x)h + G(x,h)
$$
  show that for the remainder:
  $$
\|G(x, h)\|_{H_2} \leq \frac{1}{2}N_2 \|h\|^2_{H_1}
$$

I know it should be something pretty straightforward (integration by parts was on my bet list) but I apparently couldn't converge to an appropriate answer.
Answer: Let $u\in H_2$ be a unit vector such that $\langle G(x,h), u\rangle = \|G(x,h)\|$. Consider the function
$$f(t) = \langle F(x+th), u\rangle $$
Since $f'(t) = \langle F'(x+th) h, u\rangle$, it follows that $|f'(t)|\le N_1\|h\|$ and $|f'(t)-f'(s)|\le N_2\|h\|^2 |t-s|$.  I don't think we need the first of these, actually.
The function $g(t) = f(t) - f(0) -  f'(0)t$ satisfies $g(0)=0$ and $|g'(t)|\le N_2\|h\|^2 t$, hence
$$
|g(1)| \le \int_0^1 |g'(t)|\,dt \le \int_0^1 N_2\|h\|^2 t\,dt = \frac12 N_2\|h\|^2
$$
which proves the claim because
$$
g(1) = f(1)-f(0)-f'(0) = \langle F(x+h)-F(x)-F'(x)h, u \rangle
= \|G(x,h)\|
$$


How to add a CSS class to an render array?

Question: In a template file, before print render($content['field_image']); I would like to add a CSS class to the image in the $content['field_image'] render array. How can I do this?
Here is the render array:
Array
(
[#theme] => field
[#weight] => 2
[#title] => Image
[#access] => 1
[#label_display] => hidden
[#view_mode] => full
[#language] => und
[#field_name] => field_image
[#field_type] => image
[#field_translatable] => 1
[#entity_type] => node
[#bundle] => ll_basic_page
[#object] => stdClass Object
[#items] => Array
    (
        [0] => Array
            (
                [fid] => 6777
                [alt] => alt text
                [title] =>
                [uid] => 1
                [filename] => imageFile.jpg
                [uri] => public://imageFile.jpg
                [filemime] => image/jpeg
                [filesize] => 28742
                [status] => 1
                [timestamp] => 1314312382
                [rdf_mapping] => Array
                    (
                    )
            )
    )
[#formatter] => image
[0] => Array
    (
        [#theme] => image_formatter
        [#item] => Array
            (
                [fid] => 6777
                [alt] => alt text
                [title] =>
                [uid] => 1
                [filename] => imageFile.jpg
                [uri] => public://imageFile.jpg
                [filemime] => image/jpeg
                [filesize] => 28742
                [status] => 1
                [timestamp] => 1314312382
                [rdf_mapping] => Array ()
            )
        [#image_style] =>
        [#path] =>
    )
)

And this is the HTML output:

I tried adding a class to $content['field_image']['#attributes']['class'], but that didn't work.
Do you have any idea on how I can achieve what I am trying to do?
Answer: I believe it would be:
$content['field_image'][0]['#attributes']['class'][] = 'my-class';

Or to assign it to every element,
foreach (element_children($content['field_image'] as $key) {
  $content['field_image'][$key]['#attributes']['class'][] = 'my-class';
}

Comment: Tried this but doesn't work.
Comment: Which part? The first or the second? Because both actually work.
Answer: The above solutions did not work for me (and weren't clearly described in any case). Here's the way I solved this exact problem. This is probably not the best way, and certainly not the only, but it's a valid "Drupal way" and works. Open up the template.php file for your template.
Paste in the following function, which you will have to MODIFY and customize for your usage scenario. For example, you must replace <TEMPLATENAME> with your template name, and add or subtract classes as desired, and other things, as you'll see.
function <TEMPLATENAME>_preprocess_image(&$variables) {
    // If this image is of the type 'Staff Photo' then assign additional classes to it:
    if ($variables['style_name'] == 'staff_photo') {
        $variables['attributes']['class'][] = 'lightbox';
        $variables['attributes']['class'][] = 'wideborder';
    }
}

I created an "if" statement to determine when the class should be added to the image, but you will have to customize that however you like--you might eliminate it entirely if you want a class on ALL image-field images, or you might say if (drupal_is_front_page()) if you only want it applied on the front page, etc.
In MY case, I created an image style (Configuration > Media > Image Styles) for Staff Photos and added the if clause to only apply my preferred classes to images of that specified Image Style. I think that's a great way to do it, but you can do what you like.
Now, whenever I am viewing a node which contains an image-field with image style of "Staff Photo," the classes magically appear in the IMG tag, which is just what I needed.
Answer: This issue seems fixed in core 7.23
In the node tpl add this at the top:
<?php
$content['field_name'][0]['#item']['attributes']['class'][] = 'your-class';
?>

Comment: This works for field_type=image.
Answer: You can also do something like this:
  $array['container']['#prefix'] = '
';
  $array['container']['#suffix'] = '
';

Comment: In this case, you'd be better off with `'#type' => 'container'` and the `#attributes` method above, rather than hardcoding the div and class, because then nothing can add to the class, defeating the purpose of a renderable array.
Answer: For those of you in a "field--field-image.tpl.php," use this:
$item['#item']['#attributes']['class'][] = 'your-class';

Answer: I was looking for a similar solution, but for styling a form input element and not an image.
Inside my customized commerce_coupon.checkout_pane.inc include i added an #attributes array containing the necessary classes.
So if you're looking for a module entangled solution instead of template embedded, this might be a good alternative.
Running on Drupal 7.39
  $pane_form['coupon_add'] = array(
    '#type' => 'button',
    '#value' => t('Add coupon'),
    '#name' => 'coupon_add',
    '#limit_validation_errors' => array(),
    '#ajax' => array(
      'callback' => 'commerce_coupon_add_coupon_callback',
      'wrapper' => 'commerce-checkout-coupon-ajax-wrapper',
    ),
    '#attributes' => array('class' => array('btn', 'btn-13')),

Answer: If you need some conditions to apply the class, you'll need to gather page fields informations.
You can do it with function template_preprocess_field(&$variables).
template_preprocess_field(&$variables) {
  if ($variables['element']['#field_type'] == 'image') {
        $variables['items'][0]['#item']['attributes']['class'][] = 'your-class';
  }
}


Creating a new type with a generic parameter as literal field name

Question: Here is what I'm trying to accomplish :
type Selection<K, T> = {
  selectionDate: string;
  selector: User;
  [K]: T
}

// Then :

type NodeSelection = Selection<"node", Node>
type ParamSelection = Selection<"param", Param>
// etc.

But it doesn't work that way seemingly. How should I proceed ? Thanks.
Answer: You need to intersect your object type of static keys with a mapped type representing the dynamic key, like this:
  type Selection<K extends PropertyKey, T> = {
    selectionDate: string;
    selector: User;
  } & { [P in K]: T }

Note that K has to be constrained to a keylike type (PropertyKey is an alias for string | number | symbol).
That gives you the following types:
  type NodeSelection = Selection<"node", Node>
  /* type NodeSelection = {
       selectionDate: string;
       selector: User;
     } & { node: Node; } */

  type ParamSelection = Selection<"param", Param>
  /* type ParamSelection = {
       selectionDate: string;
      selector: User;
     } & { param: Param; }*/

You can verify that this should work the way you expect.
There are other ways to write Selection, such as using the built-in Record<K,T> utility type and even ways to avoid the intersection via a single mapped type, but the above should meet your needs.  Hope that helps; good luck!
Playground link to code


Impossible to run php-fpm on server restarts (Ubuntu 12.04 x64)

Question: I'm setting up a server with nginx + php-fpm (5.4.11) on ubuntu 12.04 LTS (x64)
I installed nginx from the repository and I compiled PHP myself. Everythings work fine when I start php-fpm and nginx
sudo /etc/init.d/php-5.4.11-fpm start
sudo service nginx start

I can display a phpinfo on a webpage, so far so good.
pid is set like this in /etc/php-5.4.11/php-fpm.conf
pid = /var/run/php-5.4.11/php-fpm.pid

and from /etc/nginx/sites-available/default
location ~ \.php$ {
  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  fastcgi_pass unix:/var/run/php-5.4.11/php-fpm.sock;
  fastcgi_index index.php;
  include fastcgi_params;
}

Now, I would like to start PHP when the server reboots, so I did:
update-rc.d php-5.4.11-fpm defaults

But when I restart the server, I got this error in the log file:
ERROR: unable to bind listening socket for address '/var/run/php-5.4.11/php-fpm.sock': No such file or directory (2)

And indeed, the directory that I created myself /var/run/php-5.4.11/ has disappeared. If I create it again and do sudo /etc/init.d/php-5.4.11-fpm start, it works. But If I restart the server, the directory will be deleted and php-fpm won't start.
What's wrong, I don't get it?
Thank you very much!
Answer: Probably, tmpfs is mounted to the /var/run. In other words, this is a RAM-disk and it's clean at OS start.
In this case you should point "pid" and "listen" directives of your php-fpm pool configuration  straight to the /var/run:
pid = /var/run/php-fpm.pid

[www]
listen = /var/run/php-fpm.sock

Comment: I wonder if this work if you have multiple vhosts? What happens when they share the same path to sock and pid?
Comment: You're a legend - this saved me so much time.  In my pool.d/ config, I added a [global] override for pid=/var/run/php7.0-fpm.pid and then PHP would restart.  Thanks!


combining Gauss and Stokes theorems leads to nonsense

Question: Gauss Theorem:
$$\int_S \vec{a} \, d\vec{S}=\int_V\operatorname{div}(\vec{a})\,dV$$
Stokes theorem:
$$\int_C \vec{a}\,d\vec{l}=\int_S\operatorname{curl}(\vec{a})\,d\vec{S}$$
Combining together:
$$\int_C \vec{a}\,d\vec{l}=\int_S \operatorname{curl}(\vec{a}) d\vec{S} = \int_V \operatorname{div}(\operatorname{curl}(\vec{a}))\,dV=0$$
since $\operatorname{div}(\operatorname{curl}(\vec{a}))=0$, whats wrong here?
Comment: Should you have $\vec{a}\cdot d\vec{S}$ instead of $\vec{a}\,d\vec{S}$, i.e. a dot product?
Answer: This works only if $S$ is the boundary of $V$ and $C$ is the boundary of $S$.  But then $C = bbV$.  The boundary of a boundary is empty, and so $C$ was empty to begin with.  That is why the integral of any $1$-form over $C$ is $0$.
Comment: Viewed the other way around, if you start with a curve C which bounds an region S, there is no way that region S bounds a volume V.
Answer: The surface in the Gauss theorem must be the boundary of the volume $V$. It's not the case with $S$ the surface related to the curve $C$.
Comment: Say we have any surface that intersects xy axis and the intersection could be considered as curve C. Then surface is then closed, why doesn't that work?
Comment: I don't mean close in a topological sense. I want to say that $E-S$ must have two connected components, in order to define the volume V..
I'm going to edit.
What do you mean by the xy axis ?
Comment: Oh I just realized that Stoke's theorem does not imply closed surface, but only capping surface to curve C. Thanks.


Image map (html img usemap) in Outlook signature created by VBS script?

Question: I know it is recommended not to use image maps in emails, but that aside, how can I (or can I) create an image with a usemap tag in Outlook using VBS?
My current piece of code for inserting the logo and link is:
<code>'insert campaign banner
Set objLink = objSelection.Hyperlinks.Add(objSelection.InlineShapes.AddPicture(strCampaignBannerLoc), strCampaignURL,,,"")
</code>
This month's campaign image is a rectangle showing three events, I want a link for each event and I would like to avoid three images.
Many thanks!
Answer: The Outlook object model provides three main ways for working with item bodies:

Body - a raw text.
HTMLBody - an HTML markup which represents the body.
The Word editor. The WordEditor property of the Inspector class returns an instance of the Document class which represents the message body. So, you can use the Word object model to custimize the body.

You can read more about all of these way in the Chapter 17: Working with Item Bodies article in MSDN.


Absolute continuity on an open interval of the real line?

Question: In classical real analysis I've only seen absolute continuity defined for functions on compact interval $[a,b]$, where the two equivalent definitions are: $f:[a,b]\rightarrow\mathbb{R}$ is AC if
(1)  Given $\epsilon > 0$ there is a $\delta > 0$ such that $\sum_{i=1}^n |f(y_i)-f(x_i)|< \epsilon$ for every finite collection of nonoverlapping intervals $( (x_i,y_i) )_{i=1}^n $ each contained in $[a,b]$ with $\sum_{i=1}^n |y_i-x_i|< \delta$. Or,
(2) $f'$ exists a.e. on $[a,b]$, $f'$ is integrable on $[a,b]$, and
$f(x) = \int_a^x f'(y) dy + f(a)$ for all $x \in [a,b]$.
Is there an accepted definition for absolute continuity of a function on an open, possibly unbounded, interval $(a,b)$ where $-\infty \leq a < b \leq \infty$?
It seems that definition (1) extends easily to this case if we replace $[a,b]$ by $(a,b)$.  If we call this condition (1'), then it's easy to show (1') is equivalent to (see answer by Jonas below).  A natural extension of (2) to this case would be
(2') $f$ is AC on an open set $U$ if, for all compact intervals $[c,d] \subset (a,b)$, $f$ is AC in the sense of (2) on $[c,d]$.
Which of these is the best extension of the definition?  I don't know enough about the notion of absolute continuity of measures to know if my extended definitions are consistent with that generalization as well.
Comment: Greg: http://en.wikipedia.org/wiki/Absolute_continuity says that the its enough for $I$ to be an interval. In that case i can take $I=(-\infty,\infty)$.
Comment: Actually I am not able to answer your question but maybe these two posts Absolute Continuity I http://unapologetic.wordpress.com/2010/07/01/absolute-continuity-i/ and Absolute Continuity II http://unapologetic.wordpress.com/2010/07/02/absolute-continuity-ii/ from John Armstrong's blog (The Unapologetic Mathematician) help you.
Comment: @Americo Tavares: I think he doesn't want to make use of Measure theory, as stated in the last line of the problem.
Comment: @Chandru1: You are right!
Answer: (1') is not equivalent to (2').  For example, $f(x)=x^2$ satisfies (2') on $(-\infty,\infty)$ but not (1'). It is not even uniformly continuous.
Condition (2'), being AC on all compact subintervals, is a condition I have at least seen used, and it is the right one if you want to extend the equivalence to being an indefinite integral.  Namely, it is equivalent to:
(3) If $a\lt c \lt b$, then $f(x)=f(c)+ \int_c^x f'$ for all $x\in(a,b)$.
This is only a slight modification of (2), which must be made because $f$ may be unbounded or otherwise undefined at $a$ and $f'$ may not be integrable on $(a,x)$, even if $f$ satisfies the stronger condition (1') (e.g., $f(x)=x$ on $(-\infty,\infty)$).
But you asked if this is the "best" definition or if there is an "accepted" definition, and of that I am not sure.  I have not seen anyone write "$f$ is AC on $(a,b)$" when they mean (2') holds.  For the case $(-\infty,\infty)$, I have seen simply "f is AC on bounded intervals".  On the Wikipedia page, they use the phrase "locally absolutely continuous" in the section on the relationship to measures.
Comment: Thanks Jonas.  Still helping me even after you've graduated!
Comment: Ah, I was wondering whether you were that Greg O.!  You're welcome.  It would still be interesting to see whether (1') has any uses, being strictly between Lipschitz continuous and indefinite integral, but I don't expect anything.


Goursat proof of Cauchy Integral Theorem assumption

Question: I am studying the Goursat proof of the Cauchy Integral Theorem
It relies on the remark that the integrals $\int dz$ and $\int zdz$, taken along any closed contour are null.
I don't know how to prove that. I can imagine that $\int dz=0$ because when you return from where you went, the sum of all your trips should be null (it is not a very rigorous mathematical proof), but for $\int zdz$ it is much harder for me.
Can you help me to solve that problem?
Edit: we could use Cauchy's integral theorem for that but since it is exactly what we are looking to prove it doesn't make sense...
Comment: Do you know the theorem that $\int_{\gamma}f(z)dz$ depends only on the endpoints of $\gamma$ if  $f(z)$ is the derivative of an analytic function?
Comment: I knew that for real functions but I thought the goal of Cauchy's Theorem was to prove it for complex functions.
Comment: The goal of Cauchy's theorem is to prove this property for analytic functions at a point in the development of the theory of analytic functions when you don't yet know that every analytic function is the derivative of another analytic function. You then use the theorem as an important tool to prove that and many other important facts, e.g., that an analytic function has higher derivatives of all orders.
Comment: I can not contradict you, but it is not presented like this for example in Wikipedia or in most other resources.
Answer: The fundamental theorem calculus applies to complex differentiable functions in a similar way to how it applies to real differentiable functions. To spell it out, if $f(z)$ is complex differentiable, and if $\gamma$ is a path from $a$ to $b$, then
$$ \int_\gamma f'(z) dz = f(b) - f(a).$$
In particular, if $\gamma$ is a closed path, then $\gamma$ starts and finishes at the same place, so the $a$ and $b$ in the equation above are the same point. So if $\gamma$ is a closed path, you have
$$ \oint_\gamma f'(z) dz = 0.$$
Now if you apply this result with the differentiable functions $f(z) = z$ and $f(z) = \frac 1 2 z^2$, you will be able to deduce that $\oint_\gamma 1 dz = 0$ and $\oint_\gamma z dz = 0$ along any closed path $\gamma$.
Comment: The paper you are reading is original research: I wouldn't expect it to contain motivation for the importance of Cauchy's theorem: Goursat's readers would have been well aware of that. What they would have been interested in is Goursat's delightfully simple proof of the theorem. If you want the motivation, look at any good book on Complex Analysis, e.g., Ahlfors. (Part of the motivation is that it helps in the proof that all analytic functions have power series expansions, so that your vague "most of the time" we can find an antiderivative becomes a general theorem).
Comment: OK so Cauchy's integral theorem is only interesting for functions f(x) which we can prove that they are holomorphic but not that there exists a function F(x) such that F'(x) = f(x). It is very limited. And what is the theorem which prove that ∫f′(z)dz=f(b)−f(a), if not Cauchy's integral theorem?
Comment: The proof that $\int_\gamma f'(z) = f(b) - f(a)$ is a trivial consequence of the fundamental theorem of calculus in real analysis: $\int_\gamma f'(z) dz = \int_{t_0}^{t_1} f'(\gamma(t)) \gamma'(t) dt = \int_{t_0}^{t_1} (f \circ \gamma)'(t) dt = (f\circ \gamma)(t_1) - (f\circ \gamma)(t_0) = f(b) - f(a)$.
Comment: @JeanPaul … and as for your first comment, I must disagree! I think Cauchy's integral theorem is very powerful! For example, one of the things you can prove using Cauchy's integral theorem is that **all** holomorphic functions $f$ can be written in the form $f(z) = F'(z)$, at least in small, local regions of the complex plane!
Comment: I guess you're right but for me your formula above is the most interesting result because it's simple and in practice I think that if we can prove that a function is holomorphic then we can most of the time find a function $F(z)$ such that $f(z) = F'(z)$. I think it would have been better to be clearer about that.
Comment: Okay, fair enough!


Sum of $\frac{25^x}{25^x+5}$

Question:
Find
$$\sum_{n=1}^{1999}\frac{25^{\frac{n}{2000}}}{25^{\frac{n}{2000}}+5}$$

My work:
$$\frac{25^x}{25^x+5}=\frac{5^{2x}}{5^{2x}+5 }$$
I don't see a pattern here, and I don't think the point of this problem is to evaluate radicals. Please help!
Comment: As a target, *Mathematica* yields $999.5$.
Comment: It may be easier to see what's happening if you replace $2000$ with $4$ everywhere. So that $1999$ becomes $3$.
Comment: With $n=4$ it may be easier to see how a variant of
$$\frac{e^x}{e^x+e^{-x}}+\frac{e^{-x}}{e^x+e^{-x}}=1$$ comes into play.
Answer: Let $f(x)=\frac{25^{x}}{25^{x}+5}.$ Note that$$f(x)+f(1-x)=\dfrac{25^{x}}{25^{x}+5}+\dfrac{25^{1-x}}{25^{1-x}+5}=1.$$
So we have$$\begin{aligned}
\sum_{n=1}^{1999}f(\dfrac{n}{2000})&=[f(\frac{1}{2000})+f(\frac{1999}{2000})]+\cdots\\
&+[f(\frac{999}{2000})+f(\frac{1001}{2000})]+f(\frac{1}{2})\\
&=999+\dfrac{1}{2}=999.5.\\
\end{aligned}$$
Comment: Why does $f(x)+f(1-x)=\dfrac{25^{x}}{25^{x}+5}+\dfrac{25^{1-x}}{25^{1-x}+5}=1$?
Comment: $\frac{25^{1-x}}{25^{1-x}+5}=\frac{25}{25+25^{x}\cdot5}=\frac{5}{25^{x}+5}.$

Sum of $\frac{25^x}{25^x+5}$


Flush input in C

Question: I'm a student in software engineering and I'm on Christmas break in order to get better for the next semester I've been writing various console applications to practice. I have however ran into a problem, I need to get integer input from the user. I've been using fgets to get the string from stdin and then using sscanf to get the integer (Which has worked fine) but if the user enters more than my buffer size trailing characters are left in the stream (Including a newline with skips my next call to fgets). I've looked around and found that most people seem to suggest while(getchar() != '\n'); that however causes me a problem because if there isn't a newline character to be consumed an unnecessary scan for input takes place.
Example:
int ch;
char* buffer = (char*)malloc(BUFSIZ*sizeof(char));
while((ch = getchar()) != '\n' && ch != EOF);
fgets(buffer,BUFSIZ*sizeof(char),stdin);

If the buffer isn't too small and no trailing characters remain in the stream then there is an unecessary getchar() causing input.
Output:
A

A

You typed A

Intended Output:

A

You typed A

I hope that I made this clear enough, I appreciate any help.
Comment: Please don't use malloc to allocate a buffer, unless it's VERY large. Sooner or later, you'll forget to deallocate it. The stack (in userspace) for both Windows and Linux is several megabytes.

If, later on, you need to store the input data into some organized data structure, then you may want to malloc and free that structure. But calling malloc on small buffers that are used locally is a bad choice.
Comment: He may need to return it, you don't know the context.
Comment: could use alloca if it's not being returned. That does get freed when the function returns, but really just declaring an array is probably the way to go.
Comment: @Tomwa ivory at your place I would use only fgets.You can ignore the existence of the buffer as long as you ignore the existence of scanf and it's family functions.Remember that if the number of characters read by fgets is greater than the maximum length, the '\n' is not appended in the string, so remove it only if is actually existent in the string.
Comment: @kdubs I think that this would be longto say , so I created a chatroom: http://chat.stackoverflow.com/rooms/21486/flush-input-in-c-comments
Comment: @kdubs: far better to use `malloc()` than `alloca()`; the former is at least portable, whereas the latter is tied to the GCC infrastructure.
Comment: but who doesn't use GCC ? ... 8-)  but yes, alloca does have some issues I suppose. I use to love using it back in the day though.
Comment: @kdubs Would char buffer[BUFSIZE]; be preferable then?
Comment: that would work just fine. it will be released when you leave the function. You can't use it as a return value. just remember that.
Answer: Check whether the string you read includes a newline.

If there is a newline, you don't need to clear the input.
If there is no newline, read until you come across one.

On Unix, this loop is reasonable:
int c;
while ((c = getchar()) != EOF && c != '\n')
    ;

Note the EOF test compared with what you quoted (in the text of the question; this is what you quoted in your code snippet, but it is spread over two lines here, which is generally better for readability).  I would do this 'gobbling' after the fgets(), rather than before the next one.
On Windows with the Microsoft compilers and libraries, you can play with fflush(stdin) if you are so minded.  That has documented behaviour (see the MSDN web site).  On Unix, trying fflush(stdin) yields undefined behaviour — don't do it.
Comment: "On Windows" - for certain compilers perhaps; with gcc under Cygwin it does not flush the input.

Flush input in C


Ao submeter formulário, os dados de GET são perdidos

Question: Estou tentando enviar os dados de um form para o banco de dados. Tenho dados vindo de POST e também do GET, porém ao clicar no botão submit o valor da variável que recebe dados do GET são zerados.
ESTE É O FORM.
<form action="pedidos.php" method="post">

         NOME DO CLIENTE
         <?php echo strtoupper($nome_cliente); ?>

         PRODUTO:
         <select name="produto">
        <?php
            if(isset($selecionar_produto) && mysql_num_rows($selecionar_produto)){
                while($produto = mysql_fetch_array($selecionar_produto)){ ?>
                <option value="<?php echo $produto["id_produto"]; ?>"> <?php echo $produto["nome_produto"]; ?> </option>
        <?php
                }
            }
        ?>

         QUANTIDADE:
         <input type="number" name="qtde">

         RUA:
         <?php echo strtoupper($rua); ?>

         NÚMERO
         <?php echo strtoupper($num); ?>

         BAIRRO
         <?php echo strtoupper($bairro); ?>

         CIDADE:
         <?php echo strtoupper($cidade); ?>

         STATUS

            <select name="status">
                <?php
                    if(isset($selecionar_status) && mysql_num_rows($selecionar_status)){
                        while($status = mysql_fetch_array($selecionar_status)){ ?>
                        <option value="<?php echo $status["id_status"];?>"> <?php echo $status["status"]; ?> </option>
                <?php
                        }
                    }
                ?>

         <input type="submit" name="botao" value="Cadastrar">
         <input type="button" name="botao" value="Voltar">

            </select>

</form>

ESTE É O PHP PARA CADASTRAR O PEDIDO
   if (isset($_POST["botao"]) && $_POST["botao"] == "Cadastrar"){

        $gravar_pedidos = mysql_query("INSERT INTO pedidos(id_cliente,id_produto,id_status) values ('$id_cliente','$produto','$status')");

        if(!$gravar_pedidos){
            echo "Erro ".mysql_error();
        }else{
            echo "<meta http-equiv='refresh' content='0;URL=painel.php'/>

             ";
        }

}

Comment: edita a pergunta colocando o código do formulário html pra podermos ver como ele está e ver se o problema consiste no formulário ou no seu script. Assim que você editar a pergunta, você comenta aqui e eu dou uma olhada e vejo no que posso te ajudar.
Comment: `$id_cliente = (isset($_GET["id_cliente"]));` não está correto. Uma vez que vai ficar apenas com `true` ou `false`. O que quer fazer é `$id_cliente = ($_GET["id_cliente"]);`
Comment: Copie e cole na sua pergunta como está o html do seu formulário, e quando você mistura get e post creio que o melhor é utilizar o método que recupera ambos $_REQUEST['xxx']. [ http://php.net/manual/pt_BR/reserved.variables.request.php ]
Comment: como faço para usar o $_REQUEST? pois estou usando o post e o get
Comment: Caso alguma resposta lhe serviu, marque-a como aceita. Veja como e porque em https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Answer: sol25lua Primeiro verifique se os valores do atributo name do seu formulário são os mesmos do valor da super global POST.
Outra sugestão seria, atribuir os valores do POST antes do bloco if(e sem a função isset() e dentro do bloco do if você poderia continuar verificando se seu id está "setado" e a partir dai realizar o insert no banco de dados.
Answer: Correções a serem feitas:
1 - Acertar o html da linha PRODUTO, ou seja, fechar o select, o td e o tr

     PRODUTO:
     <select name="produto">
    <?php
        if(isset($selecionar_produto) && mysql_num_rows($selecionar_produto)){
            while($produto = mysql_fetch_array($selecionar_produto)){ ?>
            <option value="<?php echo $produto["id_produto"]; ?>"> <?php echo $produto["nome_produto"]; ?> </option>
    <?php
            }
        }
    ?>
</select>

2 - Falta recuperar os valores enviados do formulário:
    if (isset($_POST["botao"]) && $_POST["botao"] == "Cadastrar"){

        $id_cliente = $_POST['id_cliente'];
        $produto = $_POST['produto'];
        $status = $_POST['status'];

        $gravar_pedidos = mysql_query("INSERT INTO pedidos(id_cliente,id_produto,id_status) values ('$id_cliente','$produto','$status')");
         ......................

Obs: No formulário falta um campo com valores do id_cliente e o name="id_cliente"

Você pode substituir POST por GET. Aonde houver a palavra POST substitua por GET ,ou seja,
<form action="pedidos.php" method="GET">

if (isset($_GET["botao"]) && $_GET["botao"] == "Cadastrar"){
    $id_cliente = $_GET['id_cliente'];
    $produto = $_GET['produto'];
    $status = $_GET['status'];

O mais aconselhado é utilizar POST

Sobre sua pergunta
"como faço para usar o $_REQUEST? pois estou usando o post e o get"
O $_REQUEST é o tipo genérico de de $_GET, $_POST, tanto faz se seus dados estão vindo via $_GET ou $_POST, resgata ambos.
if (isset($_REQUEST["botao"]) && $_REQUEST["botao"] == "Cadastrar"){
   $id_cliente = $_REQUEST['id_cliente'];
   $produto = $_REQUEST['produto'];
   $status = $_REQUEST['status'];

Nesse caso seu formulário tanto pode ser
<form action="pedidos.php" method="post">

quanto
<form action="pedidos.php" method="GET">

Seu uso é pouco recomendado, saiba mais em Uso de $_REQUEST ao invés de $_GET, $_POST e $_COOKIE
Comment: Obrigada Leo era isso mesmo, nossa me ajudou muito.
Comment: Pelo que pude ver foi muita falta de atenção, ainda bem que tem essa fórum de ajuda


Run socket.io with ssl

Question: I'm using socket.io with node.js over express and i'm trying to run my socket over ssl/https
Everything is fine without https but i can't get it work when i try to run it with https.
This is my app.js file which i use when i write node app.js and run my socket
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};
function guid() {
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
    .toString(16)
    .substring(1);
}
// This is the main file of our chat app. It initializes a new
// express.js instance, requires the config and routes files
// and listens on a port. Start the application by running
// 'node app.js' in your terminal
var total = 0;

var usuarios = [];
var soporte = [];

var express = require('express'),
app = express();
Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

// This is needed if the app is run on heroku:

var port = process.env.PORT || 8000;

// Initialize a new socket.io object. It is bound to
// the express app, which allows them to coexist.

var io = require('socket.io').listen(app.listen(port));

io.on('connection', function(socket) {
    socket.emit('supports',soporte.length);
    socket.on('load_s',function(data){
        //seguridad.push( socket );
        soporte.push({'socket':socket,'id':socket.id});
        usuarios.forEach(function(item, index, arr){
            console.log(item)
            if(item.atendido == false){
                //socket.emit('lista',{'usuarios':usuarios});
            }
        });
        console.log("Nuevo soporte conectado");

    });
    socket.on('get_supp',function(data){

    });
    socket.on('load_u',function(data){
        var _s = socket;
        usuarios[_s.id] = {'socket' : socket, 'atendido' : false}
        console.log("Usuario en espera"+socket.id);
        //////// Buscar Soporte y asignar /////
        console.log("Soporte disponible "+ soporte.length);
        if(soporte.length == 0){
            console.log("No hay soporte disponible")
            socket.emit('no_supp');
        }else{
            /// PONER EN LISTA PARA SOPORTE
            socket.emit('wait');
            /// ENVIAR NOTIFICACION A SOPORTES
            for (i = 0; i < soporte.length; i++) {
                soporte[i].socket.emit("nuevo_usuario", {'nombre':data.nombre, 'email':data.email, 'id':_s.id, 'question':data.question,'area': data.area})
            }
        }
    });

    socket.on('new_msg',function(data){
        /// get usuario from list
        var usuario = usuarios[data.id].socket
        usuario.emit('new_msg', {'mensaje':data.mensaje,'nombre':data.nombre}); // enviar a usuario
    });
    socket.on('desconectar',function(data){
        var usuario = usuarios[data.id].socket
        usuario.emit('desconectar');
    });
    socket.on('new_msg_u',function(data){
        /// get usuario from list
        _id = socket.id;

        for ( i = 0; i < soporte.length; i++){
            if(soporte[i].id == data.id){
                soporte[i].socket.emit('new_msg', {'mensaje':data.mensaje,'id_usuario':_id}); // enviar a usuario
            }
        }
    });
    socket.on('take_user',function(data){
        /// tomar usuario ////
        console.log("usuario tomado");
        var id_soporte = socket.id // id de soporte
        var id_usuario = data.id // id del usuario
        usuarios[id_usuario].atendido = true // pasar atendido a verdadero
        for (i = 0; i < soporte.length; i++) { /// emitir usuario tomado
            if(soporte[i].id != socket.id){
                soporte[i].socket.emit("usuario_tomado", {'id':id_usuario})
                /// eliminar de la lista
            }
        }
        usuarios[id_usuario].socket.emit('atendido',{'id_soporte':socket.id});
    });
    socket.on('send_chat',function(data){
        if (data.id in departamentos) {
            // send chat , esta conectado
            console.log('conectado');
            usuarios[data.id].emit("mensaje",{text:data.text});
        }
        else{
            // send push, está desconectado
            console.log('desconectado');
        }
    });
    socket.on('send_chat_u',function(data){
        if (data.id in soporte) {
            // send chat , esta conectado
            console.log('conectado');
            soporte[data.id].emit("mensaje",{text:data.text});
        }
        else{
            // send push, está desconectado
            console.log('desconectado');
        }
    });
    socket.on('disconnect', function() {
        console.log("desconectado");
        soporte.forEach(function(item, index, arr){
            console.log(item.id+" .. "+socket.id+" ... "+index);
            if(item.id == socket.id){
                console.log("coincide");
                delete soporte[index];
                soporte.splice(index, 1);

            }else{
                item.socket.emit('usuario_desconectado',socket.id);
            }
        });
        delete usuarios[socket.id];
    });
});
console.log('Chat running' + port);

Then in my js client file i init my chat with:
socket = io.connect('https://www.xxxxxxxxx.com.mx:8000', {secure: true});

I was reading this docs:

https://www.sitepoint.com/how-to-use-ssltls-with-node-js/

But i don't know how to implement it in express (my code example which run correctly without ssl)
I have my privkey.pem and cert.pem ready to use but as i said before, i don't know how to implement it.
Thanks.
Answer: Well, finally i get it work.
socket = io.connect('https://www.xxxxx.com.mx:8000', {transports: ['websocket']});

And this is my app.js code:
var port = process.env.PORT || 8000;

// Initialize a new socket.io object. It is bound to
// the express app, which allows them to coexist.

var fs = require( 'fs' );
var app = require('express')();
var https        = require('https');
var server = https.createServer({
    key: fs.readFileSync('/etc/letsencrypt/live/www.xxxxx.com.mx/privkey.pem'),
    cert: fs.readFileSync('/etc/letsencrypt/live/www.xxxxx.com.mx/cert.pem'),
    //ca: fs.readFileSync('./test_ca.crt'),
    requestCert: false,
    rejectUnauthorized: false
},app);
server.listen(8000);

var io = require('socket.io').listen(server);

io.on('connection', function(socket) {

...

Run socket.io with ssl


Running jupyter notebook on GCP with image TF

Question: I created a VM machine from image TF (tf-1-10-cu92) to use tensorflow. I found that it includes already jupyter notebook but I can connect to it just the first time. Later I encounter an error

A connection to the notebook server could not be established. The notebook will continue trying to reconnect. Check your network connection or notebook server configuration

I search for this problem and found that maybe it is because my IP is not static so I did it. static ip
I also created a firewall rule that allows all protocols firewall rule
However, the error is not solved. I am very appreciated if someone can help me with this. Thank you
p/s: The command I used to created the VM is below:
export IMAGE_FAMILY="tf-1-10-cu92" #
export ZONE="us-west2-b" # budget: "us-west1-b"
export INSTANCE_NAME="tf-instance"
export INSTANCE_TYPE="n1-highmem-8" # budget: "n1-highmem-4"

# budget: 'type=nvidia-tesla-k80,count=1'
gcloud compute instances create $INSTANCE_NAME \
        --zone=$ZONE \
        --image-family=$IMAGE_FAMILY \
        --image-project=deeplearning-platform-release \
        --maintenance-policy=TERMINATE \
        --accelerator="type=nvidia-tesla-p4,count=1" \
        --machine-type=$INSTANCE_TYPE \
        --boot-disk-size=200GB \
        --metadata="install-nvidia-driver=True" \
        --preemptible

Answer: If you have already created a firewall rule for all IP and all protocols, what I assume is that your internal firewall might be closed or the service is not listening in any port.
I suggest you to make an nmap test such as sudo nmap -p <port> <your-server-ip>
If the result is something different to OPEN then that's the issue.
Comment: Do you mean by checking port of my GCP machine (IP found in GCP) ?

If yes then the port is actually
8080/tcp open

I can access to Jupyter notebook by taping: :8080 . The Notebook page load successful. Actually I can use jupyter the first time when I created it. Then, when I shut it down, and move to another place, I cannot use it anymore. So I guess it might come from static or dynamic IP. However, I follow a tutorial and everything is fine. When I open a notebook, it takes forever to load then an error appear "A connection to the notebook server could not be established..."
Comment: Yes, in fact, if you are using an ephemeral IP most likely you'll lose it at some point. I suggest you [reserve a static IP] (https://cloud.google.com/compute/docs/ip-addresses/reserve-static-external-ip-address) and then update all your configuration to use the one you just reserved
Comment: Yes I reserved the static IP already but it is not working.
The full error is :"A connection to the notebook server could not be established. The notebook will continue trying to reconnect. Check your network connection or notebook server configuration."
Comment: Please update your case with a nmap test for all your ports and a screenshot of your firewall rules
Comment: You find here the firewall rule: [fire wall](https://i.imgur.com/etIrrsf.png) . You can see the tensortr_rule apply for all port. However, when I try to run the nmap for all ports, it takes really long time. I used the command like this: nmap -p- -T2 -n  . Do you know another way to make it faster. Thank you a lot
Comment: If you want to determine whether the port is open or not you should wait for the output of this command, execute this nmap command without the -T2 flag  `sudo nmap -p 8080  ` and update the case with the output please