How do I embed a custom node creation form inside a view

Question: I have these nodes : Company, Cars, Trucks (cars and truck have a taxonomy term to give it's type). Cars and Trucks have a field named Company wich refer to the Company node.
So i can locate the vehicle location on a map. I know how to create a form wich allow the company's administrator to add some cars (with this subject : How do I embed a node creation form inside a view)
But i want to give a field like "Select your vehicule's type" -> "Car" or "Truck" and it shows the right form to add a new vehicle.
I want too, restrict the selection of vehicules types by user group. Then me as an administrator i want to have the possibility to select all types of vehicle, but an user group like "Motorbike Company" can use only "Motorbikes" or allow "Truck company" to use "Trucks" and Cars".
And finaly, in Campany i've a field "Vehicles" and when the company's administrator add a new vehicle, i want it add too in the "Vehicles" field of the "Company" node.
Can you help me to did that ? I use Views and Display Suite. i'm novice with Drupal and i request your help :)
Answer: As you're using plain php (not really bestpractice) you can code it out yourself there, having a select changing a query-parameter for your view (self made contextual filter ..).
A more sophisticated approach would be hooking your view, hook_views_pre_render:

This hook is called right before the render process. The query has been executed, and the pre_render() phase has already happened for handlers, so all data should be available.
Adding output to the view can be accomplished by placing text on $view->attachment_before and $view->attachment_after. Altering the content can be achieved by editing the items of $view->result.

Or create a custom page-callback (see hook_menu),
where you embed the view and add the form regarding your query param (or uri param).
You can check permissions with user_access.
You won't need to enable php execution with these approaches !
Comment: Thanks i'll search to made this. I thinking there was a solution without programming it. Let's do this !


GAE NeedIndexError:

Question: Error returned is 500 Internal server error when the running app processes a get request for ViewDogs. At GAE Stack Driver console I get:
NeedIndexError: no matching index found - recommended index is:
- kind:Dog
  ancestor: yes
  properties: -
     name: id
     direction: desc".

I confirm there is an index loaded named Dog and it currently shows "Serving"
Also confirm there are 4 dogs created successfully, and they can be queried from the DataStore Entities tab individually and with SELECT * FROM Dog.  Also note the commented out line self.response.write('You dog!') which returns as expected when uncommented, so presumably not a route issue.  I can return a single dog via GET (this code omitted) Code within class ViewAllDogs is likely faulty, did my best with the GAE docs.
index.yaml file, which I confirm is uploaded and has status: "serving"
indexes:
- kind: Dog
  ancestor: yes
  properties:- name: id
    direction: desc
  - name: name
    direction: desc
  - name: type
    direction: desc
  - name: weight
    direction: desc
  - name: boarded
    direction: desc

app.yaml file:
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: main.app

main.py
import webapp2
from datetime import datetime
from google.appengine.ext import ndb
import webbrowser
import json

def gql_json_parser(query_obj):
    result = []
    for entry in query_obj:
        result.append(dict([(p, unicode(getattr(entry, p))) for p in entry.properties()]))
    return result

class Dog(ndb.Model):
    """ Models an individual Dog """
    id = ndb.StringProperty(required = True, indexed = True)
    name = ndb.StringProperty(required = True, indexed = True)
    type = ndb.StringProperty(required = True, indexed = True)
    weight = ndb.IntegerProperty(required = True, indexed = True)
    boarded = ndb.BooleanProperty(required = True, indexed = True)

    @classmethod
    def query_dog(cls, ancestor_key):
        return cls.query(ancestor=ancestor_key).order(-cls.id)

class ViewAllDogs(webapp2.RequestHandler):
    def get(self):
#       self.response.write('You dog!')
        parent_dog = self.request.get('parent_dog')
        ancestor_key = ndb.Key("Dog", parent_dog or '*noDogs*')
        query_data = Dog.query_dog(ancestor_key).fetch(10)
        json_query_data = gql_json_parser(query_data)
        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.dumps(json_query_data))

app = webapp2.WSGIApplication([
    ('/ViewDogs', ViewAllDogs)
], debug=True)

Similar questions abound, inlcuding this Query google app engine datastore for all entities but none are solving my issue.  Thanks.
Comment: Notice the index missing is different to the index you have defined. The index you need must exactly what is required.
Comment: Have you tried it again a few minutes later? When you make changes to your queries or data structure, Datastore indexes take a few minutes to update after you deploy (maybe several, depending on the size of your data). In a production environment, you may want to use the `--no-promote` flag, wait for the indexes to update and then directing traffic to the new version deployed.
Answer: As usual, I was making it much more complicated than need be...
import webapp2, json
from datetime import datetime
from google.appengine.ext import ndb

MAXDOGS = 100

class Dog(ndb.Model):
    """ Models an individual Dog """
    id = ndb.StringProperty(required = True, indexed = True)
    name = ndb.StringProperty(required = True, indexed = True)
    type = ndb.StringProperty(required = True, indexed = True)
    weight = ndb.IntegerProperty(required = True, indexed = True)
    boarded = ndb.BooleanProperty(required = True, indexed = True)

class ViewAllDogs(webapp2.RequestHandler):
    def get(self):
        query_data = Dog.query()
        results = query.fetch(limit = MAX_SLIPS)
        aList = []
        for match in results:
            aList.append({'id': match.id, 'name': match.name, 'type': match.type,
                          'weight': match.weight, 'boarded': match.boarded})
        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.dumps(aList))

app = webapp2.WSGIApplication([
    ('/ViewDogs', ViewAllDogs)

GAE NeedIndexError:


How to show the equivalence between two definitions of completion of sigma algebra

Question: Given a Probability space $(\Omega,\mathcal{A},P)$ , I knew the definiton of the completion of a sub-sigma algebra $\mathcal{F}$ to be $\overline{\mathcal{F}}=\sigma(\mathcal{F}\cup \mathcal{N})$ where $\mathcal{N}=\{A\subset X : \exists B\in\mathcal{A} , P(B)=0\}$ .
Now I read in this that $\overline{\mathcal{F}}=\{A\subset\Omega : \exists B\in\mathcal{F},N\subset\Omega \,\text{such that}\, A\Delta B\subset N , P(N)=0\}$ .
For one side, I have done the following :-
Let $B\cup N\in \mathcal{F}\cup{\mathcal{N}}$ . Then $P((B\cup N)\Delta B)=0$ and hence $\mathcal{F}\cup\mathcal{N}\subset \overline{\mathcal{F}}$ which gives that $\sigma(\mathcal{F}\cup\mathcal{N})\subset \overline{\mathcal{F}}$.
I am really having trouble in  proceeding with the proof of the other direction . Can anyone help me with this question?
Answer: $$A = (B \cup (A \setminus B) ) \setminus (B \setminus A)$$
and $A \setminus B \subset A \Delta B \in {\cal N}$,
$B \setminus A \subset A \Delta B \in {\cal N}$.
Comment: Ofcourse!! I was being an idiot lol. Thanks


Changing to slanted coordinates

Question: In order to convert a partial derivative of an arbitrary function of two variables from Cartesian coordinates to polar coordinates, we can simply employ the chain rule as follows:
$$ \frac{\partial f(x,y)}{\partial r}=\frac{\partial f(x,y)}{\partial x}\cdot\frac{\partial x}{\partial r}+\frac{\partial f(x,y)}{\partial y}\cdot\frac{\partial y}{\partial r}=\cos\theta\frac{\partial}{\partial x}(f(x,y))+\sin\theta\frac{\partial}{\partial y}(f(x,y)). $$
This gives us a partial differentiation operator with respect to $r$:
$$ \frac{\partial}{\partial r}=\cos\theta\frac{\partial}{\partial x}+\sin\theta\frac{\partial}{\partial y}. $$
I want to extend this idea to the "slanted" Cartesian coordinate system, in which the vertical axis we now call the $u$-axis and what was formerly the $x$-axis is now called the $v$-axis and is at an angle of $\phi$ with the vertical $u$-axis, where $0<\phi<\pi/2$.
I want to find $\frac{\partial f(r,\theta)}{\partial u}$. By the chain rule:
$$ \frac{\partial f(r,\theta)}{\partial u}=\frac{\partial f(r,\theta)}{\partial r}\cdot\frac{\partial r}{\partial u}+\frac{\partial f(r,\theta)}{\partial \theta}\cdot\frac{\partial \theta}{\partial u}. $$
I'm having some difficulty in computing $\frac{\partial r}{\partial u}$ and $\frac{\partial \theta}{\partial u}$ in terms of the angle $\phi$.
Comment: Compute the Jacobian of the composite coordinate transformation.
Comment: Yes, it should be. I've edited it. I'm not entirely sure what you mean with the Jacobian calculation. What does the composite coordinate transformation refer to?
Comment: You know how to convert from polar coordinates to rectangular Cartesian coordinates and from those to the "slanted coordinates." You can either compose these two transformations and work out the matrix of partial derivatives (the Jacobian matrix) or work out the individual Jacobians and multiply them together. The partial derivatives of the inverse map can then be found by inverting this matrix.
Comment: First relate the slanted coordinates to the cartesian ones. Draw a convenient triangle.
Answer: First, let's review a way to compute partial derivative operators with respect to the polar coordinates $r$ and $\theta$. If we have a function $f:(x,y)\mapsto(u,v)$, its Jacobian matrix is the matrix of partial derivatives $$J_f = {\partial(u,v)\over\partial(x,y)} = \pmatrix{{\partial u\over\partial x}&{\partial u\over\partial y}\\{\partial v\over\partial x}&{\partial v\over\partial y}}.$$ The Inverse Function Theorem tells us that at points where $\det{J_f}\ne 0$ (with suitable conditions on $f$), $f$ is locally invertible and $J_{f^{-1}} = (J_f)^{-1}$. A practical application of this result is that a way to compute the inverse partial derivatives ${\partial x\over\partial u}$ &c is to construct the Jacobian of $f$ and invert it. The other result we'll be using is that the multivariable chain rule basically says that the Jacobian of $f\circ g$ is the product of the individual Jacobians of $f$ and $g$.
For example, for the polar-to-rectangular map $$\alpha:\pmatrix{r\\\theta}\mapsto\pmatrix{r\cos\theta\\r\sin\theta}$$ the Jacobian $J_\alpha$ is $$\pmatrix{\cos\theta&-r\sin\theta\\\sin\theta&r\cos\theta}$$ so that $$J_{f\circ\alpha} = J_f J_\beta = \pmatrix{f_x \cos\theta + f_y \sin\theta & -f_x r\sin\theta+f_y r\cos\theta},$$ as you already know from other methods.
The mapping from your "slanted" coordinates to rectangular is fairly easy to work out. It is (assuming that $\phi$ is measured clockwise) $$\beta:\pmatrix{u\\v}\mapsto\pmatrix{v\sin\phi\\u+v\cos\phi}$$ with Jacobian $$J_\alpha = \pmatrix{0&\sin\phi\\1&\cos\phi}.$$ (If the coordinate systems are related by a skew transformation instead, the matrix is slightly different, but the idea of how to use it it the same.) The partial derivatives that you're trying to compute are, per the chain rule, the elements of the Jacobian $${\partial(r,\theta)\over\partial(u,v)} = J_\alpha^{-1}J_\beta = \pmatrix{\sin\theta&\sin(\theta+\phi)\\\frac1r\cos\theta&\frac1r\cos(\theta+\phi)}.$$ Note that the derivatives with respect to $u$ don't depend on $\phi$ at all.

Changing to slanted coordinates


Loop thru 100 background-images onClick

Question: a) I have 100 body-background images
b) and a single link
The background image should change to the next one in the lot every time the link is clicked, going thru the lot one by one (would be nice if the name/number of current image also is displayed).
The images are all in a dedicated directory. jQuery is already loaded.
Anyone know where I can find the code to do this simply?
All the best...
Comment: Thank you all for your kind responses.

I owe 'zdawg' an extra strong 'thank you' for his thoughtful and informative reply and his code which does everything I asked for and works like a charm.

Issue resolved. The 'stackoverflow' community rocks.

All the best...
Answer: var allImages = ["path/to/image2", "path/to/image1"];

$(document).ready(function() {
    $("#theLink").click(function() {
        var newImageLink = allImages.pop();
        $("body").css("background-image", "url(" + newImageLink + ")");
    });
});

Answer: (added counter to gs' answer)
var allImages = ["path/to/image2", "path/to/image1"];
var counter = 0;

$(document).ready(function() {
    $("#theLink").click(function() {
        var newImageLink = allImages.pop();
        $("body").css("background-image", "url(" + newImageLink + ")");
        $("#displayhere").html(""+ counter +"");
        counter = counter + 1;
    });
});

Answer: You don't necessarily need to hard code the path to your images that way. You can name your images something like image_xxx.png, 1 - 100 and refer to that name in one place. That way if you ever need to change the name, you can easily do it in one place. Furthermore, make sure that the href attribute of the anchor tag is set to # to prevent page reloads on each click.
Here's a more complete solution that also does range checking and it wraps around when we reach our limit:

       Next

Comment: Thank you all for your kind responses.

I owe 'zdawg' an extra strong 'thank you' for his thoughtful and informative reply and his code which does everything I asked for and works like a charm.

Issue resolved. The 'stackoverflow' community rocks.

All the best...

Loop thru 100 background-images onClick


CKEditor Default File Path

Question: Using CKEditor (combined with KCFinder for file upload), when I use the browse button and retrieve my file I get the path:
<code>"/demo/cms/uploads/images/image.jpg"
</code>
Which is the path to the image, however if I then move the file around within the editor, the automatically path changes to:
<code>"uploads/images/image.jpg"
</code>
Which won't work from where the content is really being pulled. Ideally I would like both paths to be "uploads/images/" but if there is a way to modify either one that will at least make it consistent that I can overwrite the path after the content is saved.
Is there a way to modify either of the paths? I haven't been able to find the value in the docs.
Answer: Was able to use php and a regex to just strip out any path after the content is saved.

CKEditor Default File Path


Two Sample Wilcoxon Test with Different Sample Populations

Question: We were given an example the other day for Wilcoxon test with two samples with different populations ($No. untreated=n_1=4$ and $ No. treated=n_2=7$).
It was stated that:
$\mu_w=\frac{n_2(n_2+n_1+1)}{2} $
$\sigma_w^2=\frac{n_1n_2(n_2+n_1+1)}{12}$
I know that:
$\frac{W-\mu_2}{\sigma_w}\sim N(0,1)$
So two parts to this question:
How is $W$ calculated? I believe the 4 ranks (unsigned) were summed for the untreated sample.
-What is the justification for the mean and standard deviation formula? Why is $n_1$ and $n_2$ not the other way around?
Thanks.
Comment: Where did you get these formulas from?
Comment: Given these in a lecture
Answer: There are several different forms of the Wilcoxon-Mann-Whitney.
Consider this definition: $W$ = "sum of ranks in sample 2".
Under the null hypothesis, the ranks in sample 2 will be $n_2$ random draws (without replacement) from the pool of ranks, which are the numbers from 1 to $n_1+n_2$.
So we get $n_2$ values with mean $(1+n_1+n_2)/2$. Hence (by linearity of expectation) $E(W) = \frac{n_2(n_1+n_2+1)}{2}$.
So the $W$ you were given the expectation of was "the sum of ranks in sample 2".
By the same argument, the mean for the sum of ranks in sample 1 is $\frac{n_1(n_1+n_2+1)}{2}$
The mean is perhaps more easily remembered as $\frac{n_W(n+1)}{2}$, where $n_W$ is the sample size for whichever group you summed the ranks in, and $n$ is the sum of the two sample sizes.
The formula for $\sigma$ is symmetric, so it doesn't matter how the labelling goes for it.

However, with $n$'s as small as 4 and 7 I wouldn't use the asymptotic approximation, because the accuracy isn't very good in the far tails.

Good tables easily go up that far, for example*, and decent packages will compute the exact statistic.
For example, if you were doing a one-tailed test (with the alternative being that sample 1 was typically smaller) at no more than the 1% level and you got a sum of ranks in sample 1 of 11, the normal approximation would say 'reject', while the correct action would be to only reject when the sum of ranks was 10.
* If you don't have any, the probability for the end few values can be computed by hand readily enough, though, and then normal approximation should be adequate; for that sample size, the continuity correction dramatically improves the normal approximation to the cdf at W=16 and higher (it's worse for 15 and below though).
Comment: I agree, not the best but that is what the subject is dictating. Thank you for your help.


How to render a protected component using a Promise and Route

Question: Im using React-Router Version 4.1.2
The only way I can check if a user gets authenticated is via a POST API call because back-end using HTTP Only Cookie.
I have tried to the following to create a protected route, seems it return null at rendering time.
    return (
      <Route
        key={path}
        path={path}
        exact={exact}
        render={props => {
          return isAuthenticated().then(resp => {
            return <Component {...props} />
          }).catch(err => {
            window.location = '/user/login'
            return

          })
        }} />
    )

Also try async and await approach,
    return (
      <Route
        key={path}
        path={path}
        exact={exact}
        render={async props => {
          try {
            const resp = await isAuthenticated()
            return <Component {...props} />
          } catch (e) {
            window.location = '/user/login'
            return

          }
        }} />
    )

The error it generated,
Route.render(): A valid React element (or null) must be returned.
You may have returned undefined, an array or some other invalid object.

What is the correct way to make sure the user is authenticated and then render the protected component OR redirect the user to the login page if he/she is NOT authenticated?
Comment: For whomever down vote the question. leave a reason, please.
Answer: I don't know which version of react-router you are using, but I remember there is a method called onEnter in version 2.X, I think you can check the auth in these function.
so you code maybe look like this
<Router component={yourComponent} onEnter={onEnter}/>

// onEnter function.
 onEnter = (nextState, replace, done) => {
  isAuthenticated().then(res => {done()}).catch(err => {replace('new router')})
}

Comment: using 4.1.2 updated the question. `onEnter` is no longer exist in the newer version.
Answer: For the async, the error you saw was when you had not logged in. Is that correct? Try this:
return (
      <Route
        key={path}
        path={path}
        exact={exact}
        render={async props => {
          try {
            const resp = await isAuthenticated()

            return <Component {...props} />
          } catch (e) {

            return <Redirect to="/user/login" />
          }
        }} />
    )

Comment: it also happens when I am logged in.
Comment: and window.location will NOT block return
Comment: Please check your code, 1) the `` should start with an uppercase. Looks like your code is using a lowercase. 2) if it's still not working, try to return `` to test it.
Comment: my code is using `` and there is no difference between `` and  ``.
Comment: What I meant was, replacing the `` with `` to trace the problem. Apart from the authentication function, there is no problem with your code. As for your question, what is the correct way to do an authentication.. usually the authentication is done in `componentDidMount()` of the main App. The state of "logged in" or not is then saved in the state (or redux). This way, you do not have to worry with async call in route.
Comment: Hey Win, I replaced the `` to `` and the issue persists. The main component's `didMount` hook seems like a one-off way to check if the user is authenticated.
Comment: Please do share the solution here. I am curious, to be honest. Because your main route code seems ok.
Comment: I will post the solution later. I try you suggestion and it kind work.
Comment: I will be waiting then. Thanks.


Change CSS without changing the website's filetree

Question: I need to change the CSS of my current theme a bit (say, up to 100 lines).
I don't want to create a sub-theme and I don't want to directly edit my theme's files (even though it's premium theme which gets upgraded maybe once in two years so migration, in such a case, would be easy).
Rather, I want to add some global CSS which effects any current theme (given selectors are still matched), but preferably in a way which doesn't alter the website's filetree (so that if I upgrade Drupal no global CSS file will mistakenly be deleted).
Is there any way to add such "database-global-CSS" (or "database-global-JS" by which I will indirectly add the CSS), via the core? Any nasty trick?
Answer: Since you do not want to use a subtheme, I'd recommend to create a custom module to attach a custom library with your "global CSS". Simply attach the library on the appropriate preprocess_hook() and that should do the trick.
Comment: Well, it would add files, of course. But you cannot add any custom CSS/JS without either altering existing files or adding new files.
Comment: Hello, thanks, wouldn't that alter the filetree? I don't want to touch any file in the filetree.
Comment: This is the only way.
Comment: @misterdidi that may be correct for Drupal, but it's not correct for MediaWiki, for example.
Comment: @Alkalix, I was talking for Drupal only, yes. :-)
Comment: You need to alter the markup, so unless you already have something installed on the site (contrib/custom module) which lets you hack CSS into the page via the database, every in-Drupal solution will require file system changes. The other option is to stick a proxy in front of the site and rewrite it on the fly to link to a CSS file you host somewhere else online. But you're in serious over-engineering territory there
Comment: MediaWiki has nothing to do with this...
Comment: @Clive `The other option is to stick a proxy in front of the site and rewrite it on the fly to link to a CSS file you host somewhere else online. But you're in serious over-engineering territory there` with a bit more details may this be an answer? I use GitHub and call the code from there somehow.
Comment: It's out of scope for here I'm afraid, but a lot of modern proxy services probably have this feature. Cloudflare seems to for example https://www.cloudflare.com/apps/add-css
Comment: Relying on GitHub to serve CSS is unreliable - youd have to have a host and CDN. Honestly, put a 12 line CSS file in a module or theme in Drupal.
Comment: @Kevin yeah I think I see the point, thanks.


Notes sound wet on Saxophone

Question: I recently decided that I wanted to learn the saxophone and purchased one online. I've been working my way through the basics (embouchure, starting notes, etc) and I've noticed that the notes are not quite what I would expect. The notes, especially ones played with the octave key in place, sound wet. I've looked around online and the only suggestions I've found say that I should try switching the reed for a different one. I tried that today and it seemed like it might have worked initially, but within a couple of notes it sounded off again. I've cleaned out the instrument to make sure that there's not a lot of spit in it, but that didn't seem to have any effect.
I'm curious. Is this something common for a newer player and instrument and I'm personally doing something wrong, or is this a sign of something wrong with the instrument and I should have it looked at by someone more skilled?
Update
I've recorded myself playing a couple of notes. You should be able to listen to it here. (Apologies for the terrible quality. It's the best I could manage.) https://1drv.ms/u/s!AtQShntvuQPwg5Es_zx-PCyiAtlHmw
To be completely honest, it doesn't sound quite as bad in the recording as it sounds for me when I play. Also, after reading the answers below, I did notice that after playing for half an hour, there was a lot of spit in the mouthpiece, so I'm starting to think that might be the problem.
Comment: "sound wet" -- please describe by analogy to other sounds.
Comment: @CarlWitthoft I honestly can't think of a better analogy. endorph suggested bubbly which is probably the closest I can come up with. Once I'm finished with work for the day, I'll try to get an audio sample.
Answer: There's a number of possible reasons, but it does depend on what you mean by sounding wet.
If you know another sax player, ask them to play it (using their mouthpiece/reed combo). If it's fine, then you know it's you. Depending on the sax you bought, it may be the saxophone.
The specific reed might be the problem, or you might be playing on reeds that are too soft. A hard reed will make it sound breathy and hard to play, so that's probably not the issue right now.
If there's spit/condensation in the thing, it will sound bubbly or gurgly (if that's a word). Generally sucking back on the mouthpiece will clear that up.
It could also be an embouchure thing. Tone can take a while to develop, and there aren't really any shortcuts.
If you post a recording, we might be able to narrow things down. Otherwise, see if you can find another sax player who can help you out. You'll probably also get told to find a teacher, which isn't the worst idea in the world.

Here's an example of reeds that are too hard and too soft. It's taken from a video from the US Army Field Band called The Saxophone Standard. The whole thing is two hours long, but might be worth a look.
Comment: Sounding bubbly is a good way of describing it. I'll see what I can do about getting a recording tomorrow. Also, I unfortunately don't know any other sax players, but I do have a music store nearby I might be able to take it to.
Comment: Music stores don't necessarily have people on the staff who are experts in everything they sell, but they do usually know who the music teachers are - for the obvious reason that music teachers create their next generation of customers!
Comment: I have uploaded a recording.
Comment: The Saxophone Standard is a great resource, and I recommend it to everyone that is interested in the saxophone, or plays it already, even advanced students
Answer: That doesn't sound too bad for a beginner.  But it does sound like you need some lessons.  A teacher will also be able to check your instrument over of course.   But mainly they'll advise on embouchure and breathing.
Answer: It appears that your embouchure is not yet well developed, which is perfectly normal for a new player. To improve, you need to slowly work on it.
Scrap all that online stuff which asks you to roll over your entire lip and bite. If you only use part of the lip and make it firm, you will have a much more free-blowing sound. Also, with notes such as D(your first note with octave key) are very hard to sound bright on. To obtain a brighter sound, raise the tongue in the back of the mouth(touch your molars with your tongue) to speed up the airstream, hence improving dynamic range and tome.
Reeds and mouthpieces are there to enhance your sound, not there to provide the foundation.
Answer: I've been playing for 11 years. This sounds like embescoure problem. You really have to bite (with your mouth and firm cheeks) especially on the high notes to achieve the right tone.
The velocity comes from your diaprahgm, not the cheeks or mouth. Not enough air will result in a foggy or flat tone.
Also reeds, I try many while I practice because not everyone one is good, but some reeds let me achieve a certain quality over others. Start with a 2.5, below that is real bland.
Also sometimes the instrument is cold, it can be literally unplayable.
Comment: You've been playing for 11 years and you think you should achieve high notes by clamping down on the reed?  That's just plain wrong.   Advice as to reed strenght also wrong.  The proper strength depends on the choice of mouthpiece as well as the ability of the person playing to handle a given reed.
Comment: I've got 20 yrs of single-reed experience in my back pocket. I've worked with many highly qualified teachers.  "Bite down" on the reed or mouthpiece is never a correct way to play.
Comment: How long have you been playing Carl, what's your advice. How is this a even a question that could be right or wrong? It's a measure of quality. I do this every day.
Comment: This is precisely why he needs a teacher.  YOU know what you mean by 'bite down'. ...

Notes sound wet on Saxophone


Hyperjaxb @Entity

Question: How to avoid declaring fully qualified name of the derived class in @Entity annotation?
I have the following xsd:
<code><xsd:complexType name="Project">
        <xsd:annotation>
                <!-- ... -->
        </xsd:annotation>
 <xsd:sequence>
  <!-- ... -->
 </xsd:sequence>
</xsd:complexType>
</code>
but it generates the following java source:
<code>@Entity(name = "com.mycompany.db.Project")
@Table(name = "project")
@Inheritance(strategy = InheritanceType.JOINED)
public class Project
    implements Equals, HashCode, ToString
{
...
}
</code>
I need to remove explicitly name from @Entity, to be like:
<code>@Entity
@Table(name = "project")
@Inheritance(strategy = InheritanceType.JOINED)
public class Project
    implements Equals, HashCode, ToString
{
...
}
</code>
Thanks,
Comment: Why? Surely the entity name is largely irrelevant?
Comment: skaffman: Some users reported qualified names aren't actually standard in JPA.
Answer: Wow, Hyperjaxb now has an own tag on SO. :)
In the new version (0.5.5, to be released soon) HJ3 generates non-qualified entity names. See http://jira.highsource.org/browse/HJIII-34.
Comment: @lexicore Can you help me with [this](http://stackoverflow.com/questions/34065476/use-fully-qualified-names-in-hyperjaxb3-generated-java-classes) I am using version 0.5.6 but I want to have fully qualified names in `@Entity` name field ?

Hyperjaxb @Entity


having some trouble understanding a rearrangement of a cylinder equation :S

Question:
Find the surface area of the upper half of the sphere $x^2 + y^2 + z^2 = 1$ that is inside the (infinite-height) cylinder $x^2 + y^2 - y = 0.$ If the surface of the sphere has mass per unit area equal to |x|, find the mass of the above surface area.

the first line of the solution has already got me stuck, it says that the cylinder equation can be rewritten as $x^2 + (y - \frac12)^2 = \frac12^2$
can someone please explain this to me? I'm not entirely sure how they reached this! :S
Comment: The re-writing of the cylinder equation is just [completing the square](http://www.mathsisfun.com/algebra/completing-square.html) with respect to $y$.
Answer: Remember that
$\left(y - \frac12\right)^2 = y^2 - y + \left(\frac12\right)^2$.
Therefore
$$x^2 + \left(y - \frac12\right)^2 = \left(\frac12\right)^2$$
is equivalent to
$$x^2 +  y^2 - y + \left(\frac12\right)^2 = \left(\frac12\right)^2$$
which is equivalent to
$$x^2 +  y^2 - y = 0.$$
Since these equations are equivalent, any one of them is just as good
as another to use as the equation of the cylinder.
Comment: this has helped so much, i'm doing a bloody degree and I forget such a basic concept! thank you!


how can i analyse this time series

Question: How can i analyze this weird time series, i have no idea where to start ( stl decomposition ?, arima? or may be something else ...)
in brief, I am new to time series analysis and haven't developed any intuition yet. So any help would be much appreciated.
PS : the picture represents a small part of the whole dataset, but the shape is unique.

Edit :
sorry about the first version of the Q, here i add some details
the dataset is related to the environment and recorded at a daily frequency, the peaks of each level are equal, below is the plot of the whole dataset.
my goal is to forecast the past years from 2006 to 2014, but what i really need now is to understand the methodology. like when i see a weird time series like this. how can i find the best way to analyse it, what should i do at first step? before jumping to forecast.
Comment: Is your goal forecasting?
Comment: Well, there are quite obviously local levels and spikes on top of this. It looks like the spikes are all of the same height over the local level, and they seem to occur in regular time intervals. Please give us *a lot* more information. What data is this? Do you know when the jumps between local levels occur? And in what direction? What do the spikes represent? Is their timing indeed deterministic? And what is your goal, is it to forecast your series?
Answer: As was pointed out in the comments there is a lot of information that is needed but just assuming we know what's going on (shifts are 'random' so the best future level is your current one and we interpret the spikes as a seasonality which is known to us) you can use a level changepoint model with a simple seasonality measure to decompose and forecast dangerously.  I would say arima and stl is not appropriate here although I am sure you could do some massaging to get things to work nicely.
Here is something I whipped up in python:
import numpy as np
import matplotlib.pyplot as plt
import random
y = []
for i in range(10):
    y.append(np.ones(50)*random.randint(10, 30))
y = np.concatenate(y, axis=0 )
y[::10] = y[::10] + 3
plt.plot(y)
plt.show()

And we can use a dev package:
pip install ThymeBoost

Hopefully it doesn't break and we know the seasonality:
from ThymeBoost import ThymeBoost as tb
boosted_model = tb.ThymeBoost(trend_estimator = 'mean',
                              fit_type = 'local',
                              seasonal_period = 10,
                              min_sample_pct = .001,
                              seasonal_estimator = 'naive')
output = boosted_model.fit(y, forecast_horizon = 100)

Plot the components
boosted_model.plot_components()

And finally plot the forecasts:
boosted_model.plot_results()

This is more for fun, I would say you could potentially get a 'perfect' decomposition and potentially a 'perfect' forecast out of it if there was more knowledge about the process which generated it.
For example, if that segment you shared itself repeats you could have something like this:

So we have multiple 'seasonalities' which would be modelled like:
from ThymeBoost import ThymeBoost as tb
boosted_model = tb.ThymeBoost(trend_estimator = 'mean',
              fit_type = 'local',
              seasonal_period = [500, 10],
              min_sample_pct = .001,
              seasonal_estimator = 'naive')
output = boosted_model.fit(y, forecast_horizon = 1000)
boosted_model.plot_results()

how can i analyse this time series


How Change magento custom message

Question: i'm new to magento. I just want to find out which files can I go to if I want to change the magento default messages, like "Your password has been updated"
I tried to look at the magento forum but no luck
Answer: Check the locale directory:
app/locale/en_US/*.csv

this directory will contain messages and their translations into different languages, each language/locale having it's own directory:
app/locale/en_GB/*.csv
app/locale/fr_FR/*.csv

Remember to refresh the magento cache once you've updated any of the translations / messages.

How Change magento custom message


How to use Vuetify (VAutocomplete) with Laravel

Question: I'm trying to use VAutocomplete within a vue component in my laravel project.
I installed vuetify like this:
npm install vuetify

The .js with which I load the component looks like this:
import Vue from 'vue'
import Vuetify from 'vuetify'
Vue.use(Vuetify)

import 'vuetify/dist/vuetify.min.css';

import MyComponent from './components/MyComponent.vue';

const app = new Vue({
    el: '#my-component,
    components: {
        MyComponent
    },
    render: h => h(MyComponent)
});

MyComponent.vue:
<template>

      <v-autocomplete
                    label="Components"
                    :items="components"
            ></v-autocomplete>

</template>

I see the following error in the browsers console:
[Vue warn]: Error in render: "TypeError: undefined is not an object (evaluating 'this.$vuetify.lang.t')"

found in

---> <VAutocomplete>

Laravel is 5.6
Vue 2.9.6
Vuetify 2.0.2
Can someone please give me a hint to get started with vuetify? Thanks!
Answer: I had the same problem. Here is how you could solve it:
Make sure to add the correct vue and vue-template-compiler versions to your package.json.
Then remove your 'node_modules' folder and reinstall it:
npm install

You also should import the VueLoaderPlugin in you webpack.mix.js.
const VueLoaderPlugin = require('vue-loader/lib/plugin')

Your mix call should look something like this:
mix.js('resources/assets/js/app.js', 'public/js').extract(['vue'])
    .js('resources/assets/js/mycomponent.js', 'public/js')
    .sass('resources/assets/sass/app.scss', 'public/css').webpackConfig({
    plugins: [
        new VueLoaderPlugin()
    ]
}).sourceMaps();

.sourceMap() to avoid missing vuetify.js.map error.
Comment: That actually worked! Don't know exactly, what was the problem before, but now its working!
Answer: Error is because you missed a "
const app = new Vue({
el: '#my-component', <=here
   components: {
        MyComponent
    },
    render: h => h(MyComponent)
});

The other error is that you don't have ID in your template.
It should work in this way:

    <v-app id="inspire">

          <v-autocomplete
             label="Components"
             :items="components"
         ></v-autocomplete>

    </v-app>

Script:
new Vue({
el: '#my-component',
vuetify: new Vuetify(),
data () {
    return {
       components: [
           'Autocompletes', 'Comboboxes', 'Forms', 'Inputs', 'Overflow Buttons', 'Selects', 'Selection Controls', 'Sliders', 'Textareas', 'Text Fields'],
        }
    },
})

Comment: The missing ' is just a copy&paste error, but I've now added 'vuetify: new Vuetify()' and added the id.
Now I get:
```
[Vue warn]: Error in beforeCreate hook: "TypeError: Vue.observable is not a function. (In 'Vue.observable(options.vuetify.framework)', 'Vue.observable' is undefined)"
```
Comment: Check this working. https://codepen.io/anon/pen/ymMdgW?&editable=true&editors=101
Comment: As soon as I add 'vuetify: new Vuetify(),' I get the error 'Vue.observable is not a function'. I guess something could be wrong with my vue installation?


Using Spherical coordinates find the volume:

Question: Inside the surfaces $z=x^2+y^2$ and $z=\sqrt{2-x^2-y^2}$
I integrated over the ranges:
$0 \leq \theta \leq 2\pi$
$ 0 \leq \phi \leq \frac{\pi}{2}$
$0 \leq r \leq \sqrt{2}$
I get $\frac{\pi}{2}(4\sqrt{2} -4).$
There answer is the same except a $-\frac{7}{2}$ instead of the 4 at the end. Obviously I'm missing a 1\2 but I seems, I can not find it.
Comment: How did you find the limits of integration? If you can draw the area you will see that $0 \leq r \leq \sqrt{2}$ is wrong.
Comment: Have you been asked to solve the problem using spherical coordinates?
Comment: I actually just got asked to use either of the two
Comment: It is not a straightforward problem for using spherical coordinates, but it is a good problem to learn deeply spherical coordinates method.
Answer: When $z=x^2+y^2=r^2$ and $z=\sqrt{2-x^2-y^2}=\sqrt{2-r^2}$ intersect each other, you will have $$r=1$$ This means that $z=1$ and $\tan(\phi)=1$. So the range of changing for $\phi$ will be $\pi/4\leq\phi\leq\pi$. While typing, I saw @Mhenni did it completely, so I am ending. :-)
Comment: +Wow.Very nice.@Babak S.
Comment: Awesome graph!! +1 $\ddot\smile$
Answer: This problem is actually better suited for cylindrical coordinates:
$$\begin{align}\int_{0}^{2\pi}\int_0^1\int_{r^2}^{\sqrt{2-r^2}}rdzdrd\theta&=2\pi\int_0^1(r\sqrt{2-r^2}-r^3)dr\\&=2\pi(-\frac{1}{3}(2-r^2)^{3/2}-\frac{r^4}{4})\mid_{0}^1\\&=2\pi(-\frac{1}{3}-\frac{1}{4}+\frac{2\sqrt{2}}{3})\\&=\frac{\pi}{3}(4\sqrt2-\frac{7}{2})\end{align}$$
The problem with spherical coordinates here is that the radius is a (piecewise) function of the azimuthal angle, which makes the integration a bit more difficult.
Answer: A related problem. The title of your problem asks for the use of spherical coordinates. You got the wrong integral limits. Note that, $ \rho $ (I am using $\rho$ instead of $r$) is bounded from above by two different surfaces. The sphere when $ 0 \leq \phi \leq \frac{\pi}{4} $ and the parabolic when $\frac{\pi}{4}  \leq \phi \leq \frac{\pi}{2} $. So, we have
$$ V = \left(\int_{0}^{2\pi}\int_{0}^{\pi/4}\int_{0}^{\sqrt{2}}+\int_{0}^{2\pi}\int_{\pi/4}^{\pi/2}\int_{0}^{\frac{\cos(\phi)}{\sin^2(\phi)}}\right)\rho^2\sin(\phi)d\rho d\phi d\theta. $$
I leave it here for you to do the calculations.
that, for $0\leq \rho \leq \frac{\cos(\phi)}{\sin^2(\phi)}$, we used the equation $z=x^2+y^2$ to get . I leave it here for you to do the calculations.
Notes:
1) To get $\rho = \frac{\cos(\phi)}{\sin^2(\phi)}$ use the equation $z=x^2+y^2$ and the spherical coordinates of $x,y,$ and $z$.
2) The integral
$$ \int \frac{\cos^3(\phi)}{\sin^5(\phi)}d\phi = \int \cot^3(\phi) \csc^2(\phi) d\phi=-\frac{1}{4}\cot^4(x). $$
Answer: This was a trick problem from the book, use cylindrical. Notice it said, "when suitable". They are not circles.


Evento teclado não funciona Jquery

Question: Gostaria de saber porque este evento não funciona com algumas teclas. A tecla que desejo é a seta para baixo (40), mas esta não funciona. Já as teclas Enter (13) e as letras e números funcionam normalmente. Já removi todo o código Jquery, e nada.
$('input[name=buscar]').keypress(function(e) {
    console.log(e.which);
    if(e.which == 40) {
        alert('You pressed enter!');
    }
});

Answer: Você deve utilizar o evento keydown neste caso, porque o evento keypress não será disparado por teclas que não são "imprimíveis", como as setas do teclado, por exemplo.

The keypress event is sent to an element when the browser registers
  keyboard input. This is similar to the keydown event, except that
  modifier and non-printing keys such as Shift, Esc, and delete trigger
keydown events but not keypress events. Other differences between the
  two events may arise depending on platform and browser.

Notas

O evento keydown pode ser utilizado para capturar as teclas Shift,
ESC e Delete
O evento keypress na verdade pode capturar as setas do teclado em alguns browsers, mas o keydown é mais confiável para este cenário, conforme indica a própria documentação
Você deve utilizar as propriedades .ctrlKey , .altKey e
.shiftKey do objeto event para verificar se as teclas ctrl, alt
e shift foram disparadas

Código funcionando com keydown

$('input[name=buscar]').keydown(function(e) {
    console.log(e.which);
    if(e.which == 40) {
        alert('You pressed enter!');
    }
});

<input type="text" name="buscar" />

Fonte:
https://stackoverflow.com/questions/19347269/jquery-keypress-arrow-keys
https://api.jquery.com/keypress/

Evento teclado não funciona Jquery


What does "chi" mean and come from in "chi-squared distribution"?

Question: What does "chi" mean and come from in "chi-squared distribution"? Does "chi" mean a random variable with a standard normal distribution? Thanks!
Answer: Chi is a Greek letter. The canonical modern history references are Karl Pearson's introduction of the chi-square test in 1900 and R.A. Fisher's work in 1924, but there is ancient history too: F.R. Helmert in 1876 deserves more than a nod.
http://jeff560.tripod.com/c.html is a good start, especially if other historical bits and pieces are of interest. It includes links. Books such as Anders Hald's histories say more.
Chi appears to be just notation that Pearson used.
Comment: +1 A couple of tidbits: Early on, the distribution of the square root of a chi-squared r.v., the [chi distribution](http://en.wikipedia.org/wiki/Chi_distribution) ($\chi$-) was more widely used than now; useful for standard deviations. E.g. you can occasionally see in old papers or books people writing about the $t$ distribution as the distribution of the ratio of a normal to an independent (scaled) chi. One advantage of it (but not the original motivation for it) was that the normal approximation kicks in much faster (this is pre-Wilson-Hilferty); handy when tables tended to be quite limited.


Saving more than one value to a Dictionary key in a loop with an Array

Question: I have this block of code
<code>//start of the loop
if let objects = objects as? [PFObject] {
    for object in objects {
        //saving the object
        self.likerNames.setObject(object["fromUserName"]!, forKey: saveStatusId!)
   }
}
</code>
likerNames is an NSMutableArray declared earlier, saveStatusId is a string I also declared and saved earlier (It's just an objectId as a String), and object["fromUserName"] is an object returned from my query (not shown above).
Everything is working fine as it is but my query sometimes returns more than one object["fromUserName"] to the same key which is saveStatusId. When this happens the value I have for that saveStatusId is replaced when I actually want it to be added to the key.
So want it to kind of look like this
<code>("jKd98jDF" : {"Joe", "John"})
("ksd6fsFs" : {"Sarah"})
("payqw324" : {"Chris", "Sarah", "John"})
</code>
I know you can use Arrays but I'm not sure how I would go about that to get it to work in my current situation.
So my question would be how to I get my key (saveStatusId) to store more than one value of object["fromUserName"]?
Answer: Something like this could work
<code>let key = saveStatusId!
let oldValue = self.likerNames.objectForKey( key ) as? [String]
let newValue = (oldValue ?? []) + [ object["fromUserName" ] ]
self.likerNames.setObject( newValue, forKey: key )
</code>
If likerNames has an array in slot[saveStatusId], append the new value, otherwise create an array and put that in the right slot
Comment: This seems like it would work but I get an error in the third line (newValue) saying "AnyObject is not convertible to String." And when I try to downcast it to a String it tells me "Binary operator '+' cannot be applied to operands of type '(String)' and '[AnyObject?]'"
Comment: object["fromUserName"] as! String
Comment: I should have mentioned, the errors on "(oldValue ?? [])"


passphrase type page for a raffle

Question: I was planning on using this password type style to let users check if they won. The codes are sent in an email then they come here to check if they won. If this was just for one winner the current system would work but i would like to add 5 and confirmPassword only allows one "code" to be valid. Is there anyway to add multiple valid ones?
<form>
    ENTER YOUR RAFFLE NUMBER HERE

    <input type="password" id="pswd" class="box" placeholder="test" onkeydown="if (event.keyCode == 13) {document.getElementById('btnSearch').click(); return false;}"/>

    <input type="button" class="confirm" id="btnSearch" value="Check Results" onclick="checkPswd();" />
</form>

Comment: You know, when you declare the `confirmPassword` variable in your JavaScript, it's client-side, meaning whoever visits your page can view the code simply by pressing `Ctrl + U` in their browser.
Comment: yes I am aware, the reason im not worried about that is that im going to confirm it through seeing if that user was truly sent that code in their email or not. Thank you for the heads up tho!
Comment: Ah, that makes sense.
Answer: You can use array in Javascript:
const confirmPassword = ["SampleCode1", "SampleCode2", "SampleCode3","SampleCode4","SampleCode5"];
if(confirmPassword.includes(password)){
}

Comment: Thank you so much! Completely solved it!!!!

passphrase type page for a raffle


How to vectorize this 2 loops in Pytorch (Difficult)

Question: How to vectorize this:
vocab_size = 20
batch_size = 2
input_len = 5
output_len = 10
input_ids = torch.randint(0, vocab_size, (batch_size, input_len))
output_ids = torch.randint(0, vocab_size, (batch_size, output_len))

print(input_ids)
print(output_ids)

tensor([[ 0,  8,  7, 12,  8],
        [14, 15,  9,  7, 10]])
tensor([[ 2, 8,  3, 15,  2, 19,  7,  1, 19,  8],
        [10,  8,  0,  7, 16,  0,  6,  2, 16, 13]])

Basically, the new value in output_ids gonna be batch_size + index of the k_th of that value in the input_ids because that value might appear multiple times in the input_ids and output_ids as well. So if that value appears for the second times in the output_ids, its' gonna be replace by vocab_size + the 2nd index of that value in the input_ids (Though my code above only get the first appearance). I change the value of output like an example (the 21 and 24 at the first row in the output)
This is what I want:
#%%
for i in range(batch_size):
    for k, value in enumerate(output_ids[i]):
        if value in input_ids[i] and value not in [0, 1, 2]: # mean that I will ignore values 0, 1, 2
            output_ids[i][k] = vocab_size + torch.where(input_ids[i] == value)[0][0]
output_ids

tensor([[ 2, 21,  3, 15,  2, 19, 22,  1, 19, 24],
        [24,  8,  0, 23, 16,  0,  6,  2, 16, 13]])

Comment: What should be done if a value appears twice in the `output_ids` but only once in the `input_ids`?
Comment: So the new value = batch_size + index of that value in the input_ids. Okay so more general it gonna be the latest appearance in the input_ids. I think you know what I mean (sorry for my eng) like it appear 3 times in output ids and 2 times in input_ids so. the value of the last 2 ones in output ids gonna have the same new value (get the index of the possible latest of input_ids)
Answer: I have come up with this vertorization version, which is not optimized in term of memory because of the use of .clone()
output_ids_para = output_ids.clone()

## Equivalent to the reverse second condition of the if statement,
## that's why there is "~" notation below.
mask = (output_ids != 0) * (output_ids != 1) * (output_ids != 2)

## Replace with a value that does not appear in input_ids
output_ids_para[~mask] = vocab_size + 9999

## Parallelize the comparison (first condition of the if statement + torch.where())
input_ids_expand = input_ids.unsqueeze(-1).expand(batch_size, input_len, output_len)
output_ids_expand = output_ids_para.unsqueeze(1).expand(batch_size, input_len, output_len)
indices_i, values, indices_k = torch.where(input_ids_expand == output_ids_expand)

## Handle the duplicated values and indices
stacked, idx, counts =  torch.unique(torch.stack((indices_i, indices_k), dim = 1), dim =0, sorted=True, return_inverse=True, return_counts=True)
_, ind_sorted = torch.sort(idx, stable=True)
cum_sum = counts.cumsum(0)
cum_sum = torch.cat((torch.tensor([0]), cum_sum[:-1]))
first_indicies = ind_sorted[cum_sum]

indices_i, indices_k = indices_i[first_indicies], indices_k[first_indicies]
values = values[first_indicies]

## The newly assigned output_ids
output_ids_para[indices_i, indices_k] = vocab_size + values

## Return the value that does not satisfy the second condition of the if statement
output_ids_para[~mask] =  output_ids[~mask]

output_ids_para

Comment: Thank you for your effort. I'll test your approach soon, but you might  want to check the above comment  as it give additional rules
Comment: The additional rule really complicates things up. You basically change `torch.where(input_ids[i] == value)[0]["0"]`  to `min(ocurrence, total_occurences)`, which I haven't seen a way to vectorize that.


Apache Camel single instance of a route running in cluster using database

Question: I have Apache Camel application deployed on two servers and they consume from JMS endpoint. I want to make sure that only one camel route is consuming from jms endpoint at a time. The only option that I can use for clustering is using database as a lock store. Does Apache Camel provide such a feature?
Answer: I think the easiest way is to consume from a topic and not a queue.
On connection, use the same subscriptionName. Only the first connection will be allowed as far i know.
Comment: topic subscriptions even if shared using JMS 2.0 shared subscription spec results in load balancing of the messages between two competing consumers


Executar comando SQL no terminal

Question: Estou querendo executar comando sql através do prompt do Windows mas não sei quais as configurações iniciais pra se fazer isso.Alguém pode me dizer?
Detalhe:Tem de ser no terminal do windows.
Comment: Que configurações? Pedidos de softwares/tutorias estão fora do escopo do site. Recomendo a leitura da [tour] e [ask]. Tentou registrar o executável do postgres (via linha de comando) no PATH (variável de ambiente) do windows ?
Comment: Sugiro alterar o título: Como executar comando SQL no terminal?
Comment: Alguma resposta resolveu o que estava em dúvida? Precisa que algo mais seja melhorado? Acha que é possível aceitá-la agora?
Answer: Utiliza a ferramenta psql, presente na instalação do PostgreSQL.
Para logar, digite:
psql -U usuarioDoBanco nomeDeUmBanco

Depois, pode executar comandos, como:
select datname, oid from pg_database;

Imagem de comando para conexão no terminal:
Comment: Sim, o psql é no terminal!
Comment: tem de ser no terminal !!
Comment: Muito obrigado ,entendi
Answer: segue um exemplo sem precisar se logar
psql --command="select codigo from produto where codigo = 'codigo_do_produto'" --host=localhost --port=5432 --username=postgres --dbname=banco

Comment: Esta resposta foi sinalizada como de baixa qualidade devido ao tamanho ou conteúdo. Por favor, se possível e se esta for uma solução ao problema, explique melhor como você o resolveu. O código pode ser trivial para você, mas para outros usuários pode não ser.

Executar comando SQL no terminal


Como personalizar o erro 404 usando HttpNotFound?

Question: Segue o código abaixo:
Controller:
if (id == null)
{
    //Response.StatusCode = 404;
    return HttpNotFound();
}

View:
@{
    Layout = null;
}

Página não encontrada

Adicionei novo código web.config:
<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
  <error statusCode="404" redirect="/404.cshtml" />
</customErrors>

Resultado final:

Aqui está path: Views/404/404.cshtml
Alguma solução ?
Comment: Cê tá testando local?
Comment: Muda pra `customErrors mode="On"`
Comment: Veja a resposta.
Answer: Pra você poder testar localmente, o mode do customErrors precisa ser On. Isso porque o RemoteOnly serve apenas para que estas páginas apareçam fora do ambiente de desenvolvimento.
Eu não tenho certeza se o redirect pode ser diretamente uma página CSHTML, acho que não, até porque não faria sentido.
Se você vai utilizar uma página completamente estática, use uma página HTML mesmo. Se for precisar de dados do servidor, faça o redirecionamento para uma action dentro de um controller.
Acho que essa segunda forma é bem melhor, até porque segue um padrão (possivelmente seu projeto todo é assim) e deixa tudo mais dinâmico, caso seja necessário personalizar a mensagem ou afins.
Observação: remova o redirectMode="ResponseRewrite" se for usar desta maneira.
<customErrors mode="RemoteOnly">
  <error statusCode="404" redirect="~/Erro/NaoEncontrado" />
</customErrors>

E faça um controller normal pra receber esta requisição.
public class ErroController : Controller
{
    public ActionResult NaoEncontrado()
    {
        return View("CaminhoDaView");
    }
}

Comment: Obrigado jbueno, funcinou aqui.


Why does pacemaker start on the secondary node instead of the primary?

Question: I have two Linux nodes running httpd service.
When I try to add the httpd resource on the primary node, the service starts on the second node instead of starting on the primary.
What am I missing here?
Initial settings:
node vpc-storage-primary \
        attributes standby="off"
node vpc-storage-secondary \
        attributes standby="off"
property $id="cib-bootstrap-options" \
        dc-version="1.1.9-55.2-2db99f1" \
        cluster-infrastructure="classic openais (with plugin)" \
        expected-quorum-votes="2" \
        stonith-enabled="false" \
        no-quorum-policy="ignore" \
        migration-threshold="2" \
        last-lrm-refresh="1370680015"
rsc_defaults $id="rsc-options" \
        resource-stickiness="100"

crm_mon:
Last updated: Sat Jun  8 09:41:20 2013
Last change: Sat Jun  8 09:28:49 2013 via cibadmin on vpc-storage-primary
Stack: classic openais (with plugin)
Current DC: vpc-storage-primary - partition with quorum
Version: 1.1.9-55.2-2db99f1
2 Nodes configured, 2 expected votes
0 Resources configured.

Online: [ vpc-storage-primary vpc-storage-secondary ]

The service I would like to add on the primary:
crm configure primitive httpd lsb:httpd \
    op monitor interval="30s" timeout="60" \
    op start interval="0" timeout="60" \
    op stop interval="0"

Answer: The setting that is missing is the preferred node.
You can first add the resource, and configure the preferred node to run it afterwards.
It is recommended to assign a weight below the stickiness of the resource to avoid unwanted downtime in the case of failover.
Check the pacemaker docs for a complete example.


How to compute characteristic polynominal of two conics

Question: If I have two conics defined as $A: XAX^T$ and $B: XBX^T$ how can I expand characteristic polynomial $f(\lambda) = det(\lambda A + B) $ so that it can be computed by a computer program or Matlab?
Comment: and what's the problem with $\det(\lambda A + B)$? Maple will understand
Answer: Most maths programs are able to calculate the determinant of a matrix. Especially MatLab (Matrix Laboratory).
Use "x = sym('x')" for symbolic calculations.
Eg:

x = sym('x');
A = eye(3);
B = [1,2,3;4,5,6;7,8,9];
det(A*x + B)

Output will be : $$x^3 + 15x^2 - 18x$$


How to numerically iterate the following equation/have I done this correctly?

Question: I'm following a method that my company uses for the structural analysis of a component, and one of the steps requires me to numerically iterate the following equation below to solve for one of the variables.
Ramberg-Osgood Stress-Strain Equation
I need to solve for sigma_b, and I know the values of all of the other variables. Specifically, the method states "Solve for sigma_b by means of numeric iteration". I'm pretty rusty on my numeric integration methods, but I took a shot at it.

First, I rearranged the equation to get sigma_b (technically "x_new"?) on the left side, and sigma_b ("x_old"?) on the right side as well mixed together with the other variables.
I then plugged in a starting value for "x_old" and calculated "x_new".
At this point, "x_new" becomes "x_old", and I recalculate a new "x_new".
Using excel, I coded this and iterated a few times until the change in my answer was very low.

Here's what I rearranged the equation to (Step 1): Ramberg-Osgood Equation rearranged
Here's a screenshot of my excel sheet (steps 2-4): Excel Iterations
Lastly, here are the four known values:
ε_ = 0.022
n = 18.77
E = 10300000
σ_0.2 = 58000
Comments, concerns? Did I rearrange the equation correctly? Better (but still practical!) method of numerical iteration? Any help is much appreciated! Apologies, my account is too new to directly embed images.
Comment: Welcome to MSE. It is in your best interest that you type your questions (using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)) instead of posting links to pictures.
Answer: First of all, Welcome to the site !
Changing notations to make the problem simple, you want to solve for $x$ the equation
$$y=a x+b x^n$$ where $a$, $b$, $n$ and $y$ are positive numbers ($a,b,n$ being given).
Looking at your results, I am sure that Newton method will converge much faster.
What we already know is that function $y$ is bracketed by $(a+b)x$ and $(a+b)x^n$. So, this provides a finite range for $x$
Edit
As you gave it, the equation is
$$\epsilon_b=\frac{\sigma_b}E +0.002 \left(\frac{\sigma_b}{\sigma_{0.2}} \right)^n$$ (we shall discuss later about it).
With the numbers you gave in the post, namely $\epsilon_b=0.022$, $E=10300000$, $\sigma_{0.2}=58000$ and $n=18.77$, being lazy (at least for the time being), let us ignore the first term and start iterating with
$$\sigma_b^{(0)}=\sigma_{0.2} \,(500 \,\epsilon_b)^\frac 1n $$
The successive Newton iterates will be
$$\left(
\begin{array}{cc}
 n & \sigma_b^{(n)} \\
 0 & 65903.694 \\
 1 & 64898.111 \\
 2 & 64736.640 \\
 3 & 64733.037 \\
 4 & 64733.035
\end{array}
\right)$$ which is quite fast (but does not have much to do with your result.
What you should notice is that we started with an overestimate of the solution; but at this point, the second derivative of the rhs is positive. Then, by Darboux theorem, the convergence is ensured without any other overshoot of the solution.
Now, let us look at what higher oder methods would give
$$\left(
\begin{array}{cccc}
n & \text{Newton} & \text{Halley} & \text{Householder} \\
 0 & 65903.694 & 65903.694 & 65903.694 \\
 1 & 64898.111 & 64743.181 & 64733.147 \\
 2 & 64736.640 & 64733.035 & 64733.035 \\
 3 & 64733.037 &  &  \\
 4 & 64733.035 &  &
\end{array}
\right)$$
Back to the equation, I must say that I would prefer to write is as
$$\epsilon_b=\frac {\sigma_{0.2}}E \left(\frac{\sigma_b}{\sigma_{0.2}} \right) +0.002 \left(\frac{\sigma_b}{\sigma_{0.2}} \right)^n$$ and define $x=\frac{\sigma_b}{\sigma_{0.2}}$. Making it more general, the equation becomes
$$\epsilon_b=a x+ b \,x^n \qquad \text{where} \qquad a=\frac {\sigma_{0.2}}E\qquad \text{and} \qquad b=0.002$$ and use as a starting point
$$x_0=\left(\frac{\epsilon_b} b\right)^{\frac 1n}$$
Comment: Thank you Claude, I'd really appreciate that! Here are the values:

ε_ = 0.022
n = 18.77
E = 10300000
σ_0.2 = 58000

I've also updated the main post to include these values.


Is there a way to organize my model files so that ruby/rails doesn't get confused?

Question: So, my list of models in app/models is getting kinda long, and I'd like to organize it.
but, I'm aware of Ruby/Rails' naming convention for folders / sub classes.
i.e.
Object::MyObject::SubObject

would look like this:
object.rb
object/
-- my_object.rb
-- my_object/
-- -- sub_object.rb

at least to my understanding
but, what I want to do is group classes that are related to each other or interact a lot.
Here is what I would like to do (as an example, these aren't my actual classes):
app/models/
-- library_item.rb     # LibraryItem < ActiveRecord::Base
-- library_items/
-- -- book.rb          # Book < LibraryItem
-- -- book/
-- -- -- page.rb       # Page < ActiveRecord::Base
-- -- -- cover.rb      # Cover < ActiveRecord::Base
-- -- magazine.rb      # Magazine < LibraryItem
-- -- magazine/
-- -- -- shiny_page.rb # ShinyPage < ActiveRecord::Base

is this possible?
I know it is with Java, but Ruby and Rails have a very specific way of doing things, and I haven't ever read anything much about organization of large projects.
Comment: It's not necessarily just a Rails convention, but a Ruby one as well. Folders represent a nested "namespace" for the class.
Comment: yeah, I really like that ruby does that. though, sometimes it can be counter-intuitive for organization / not wanting really huge lists of classes
Answer: For Rails to automatically find these models, the class names need to match the file path, e.g.:
class LibraryItem::Book::Page < ActiveRecord::Base

Personally I prefer to keep my model hierarchy mostly flat so I that I can just type Page instead of LibraryItem::Book::Page. You can accomplish both of these things -- a file hierarchy plus short model names -- by explicitly loading your models, perhaps in an initializer.
Comment: will that mess with their database tables? for your example, will that class still correspond to the 'pages' table?
Comment: @TheLindyHop, it should. If you have a problem with that use the `set_table_name` declaration.
Comment: just saw your edit, what do you mean by explicitly loading models in an initializer? Does that somehow remove the need to use the Prefexis on the class?
Comment: @TheLindyHop: Yes, e.g. put `load 'app/models/library_items/book/page.rb'` in an initializer, and then the `Page` model is already loaded, so Rails doesn't have to go looking for it. But then you have to maintain the initializer as you change/add models.
Comment: yeah, there are always trade offs. I think as long as I document well, it shouldn't be an issue. I'm going to talk to another dev, and see if he thinks it makes more sense the simple way (not have all the :: stuff) or having actual class paths - which technically would make semantic sense.. Is there a performance / speed difference between either method that you know of?
Comment: @TheLindyHop: pre-loading models can slow down start up. There may be a patch somewhere to make Rails recursively search the whole app/models tree for missing classes, which would be slower if more convenient.


NavigationManager.NavigateTo() does not work after running a method

Question: looking desperately for some help...
I have a .Net7 server-side Blazor app that is working as expected (sort of). I have added a login page where the user puts in their Username and Password into the screen and hits submit. What should happen then is

Check there is data in the Username and Password, displaying an alert if not
Run a method that triggers a Stored Procedure on the database (I use ADO and not EF)
Count the number of items in the List<Family> (this is created in the above method)
Navigate to a new page where the count is greater than 0 or display an alert if not

OK. The problem lies in the method somehow. When I run the code, the List<Family> is populated from the database. I can do the check in the razor component and I can see I have more than 1 item in the list or not. When the check is done, I can then either trigger the navigate method or the alert methods and it runs through those in debug. The issue is that in the UI the screen does not change to the new page or when an alert is expected does not display.
No error messages are displayed just the originating screen.
Ah, you may think, this is a problem with the Navigate or Alert methods!!! Well, if I place the navigate and/or the alert methods before the GetFamilies() method (which populates the list<Family> the navigation and/or the alert works fine.
What I don't understand is why :( I have removed all the async methods so it should run synchronously. I have re-coded this loads of times and ways including using a cache, using async, using Task.WaitAll(). It seems where the app needs to contact the database something happens that means although the code is run it doesn't update the UI. I have even checked the Threads and going into the GetFamilies() is the same coming out and during the method.
Note that the ReturnData.GetFamilies() method works fine and does not use anything async and is a different method to GetFamilies() in this razor page.
Can anyone suggest where I am going wrong?
Form in the Blazor component
<form>

        Username
        <input @bind="LocalLogin.UserName" type="text" class="form-control" id="userName" aria-describedby="userNameHelp" placeholder="User Name">

Please use the username and password provided with your invite.

        Password
        <input @bind="LocalLogin.Password" type="password" class="form-control" id="userPassword" placeholder="Password">

    <button type="submit" class="btn btn-primary" @onclick="() => Authenticate()">Submit</button>
</form>

Authenticate Method
    private void Authenticate()
    {
        if (!ValidLoginDetails())
        {
            return;
        }
        GetFamilies();
        if(Families.Count > 0)
        {
            Navigate();
        }
        else
        {
            Alert("Your credentials have not been recognised");
        }
    }

Get Families method
    private void GetFamilies()
    {
        string localConnectionString = config.GetConnectionString("SQLServerConnection");
        Families = ReturnData.GetFamilies(localConnectionString, LocalLogin);
    }

Navigate and Alert Methods
    private void Navigate()
    {
        navManager.NavigateTo("/ufr", true, true);
    }

    private void Alert(string argMessage)
    {
        js.InvokeVoidAsync("alert", argMessage);
    }

Answer: Replace
<button type="submit" ...>Submit</button>

with
<button type="button" ...>Submit</button>

You have a <form> with an actual submit button. That will do an actual POST to your server and that won't be handled.
Even better would be using an <EditForm> but that's a matter of choice.


Pearson chi square test: Why not sum only over independent cells?

Question: To compute the test statistic $\chi^2$ the sum is typically performed over all cells in a table, see e.g. https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test
The $\chi^2$-distribution is the distribution of a sum of the squares of k independent standard normal random variables.
So, I wonder why the sum to compute the test statistics is not only over the cells that are independent: sum over as many cells that there are degrees of freedom. E.g. in the case of a homogeneity test: just sum $(row-1)(column-1)$ cells.
I stumbled over this question by simulating the $\chi^2$-distribution for some examples from the corresponding null hypothesis. The simulated sample distribution fits the $\chi^2$-distribution better if I only perform the sum over independent cells. However, in textbooks the sum is over all cells.
Thanks for your answer.

Here is the simulation (Is constraint correctly implemented?).
Contingency table for the expectation, if X and Y are independent:
<code>           Y
        0  |  1   |
   0  | 24 |  16  | 40
X  1  | 36 |  24  | 60
-------------------
        60   40     100
</code>
<code>t=10 #
data = np.array([[35,5],[25,35]]) *t # contingency table

# We want to test for independence, the expectation is
expected = np.array([[24,16],[36,24]]) *t

# simulation under the constraints
sim00 = np.random.binomial(n=100*t, p=24/100, size=10000000)
simulation = np.zeros((10000000, 2, 2))
simulation[:,0,0] = sim00
simulation[:,1,0] = 60*t - sim00
simulation[:,:,1] = np.array([40*t, 60*t]) - simulation[:,:,0]

# sum over all cells
sample_distribution = ((simulation[:,:,:]-expected[:,:])**2/expected[:,:]).sum(axis=1).sum(axis=1)
# the independet cell - you have to comment one out
sample_distribution = ((simulation[:,0,0]-expected[0,0])**2/expected[0,0])

# plot the simulation and the chi2 distribution
x = np.linspace(scipy.stats.chi2.ppf(0.3, df), scipy.stats.chi2.ppf(0.999, df), 100)
plt.plot(x, scipy.stats.chi2.pdf(x, df), 'r-', lw=2, alpha=0.6, label='$\chi^2$-pdf')
plt.hist(sample_distribution, bins=100, density=True, label='sampling')
plt.legend();

</code>

Update: The simulation (with the full sum) gives the expected result if the simulation is done with a hypergeometric_distribution.
<code># https://en.wikipedia.org/wiki/Hypergeometric_distribution#Working_example
nb_simulations=100000
s00 = np.random.hypergeometric(ngood=40*t, nbad=60*t, nsample=60*t, size=nb_simulations)
s = np.ndarray((nb_simulations, 2, 2))
s[:,0,0] = s00
s[:,0,1] = 40*t-s00
s[:,1,0] = 60*t-s00
s[:,1,1] = 60*t-s[:,1,0]
sample_distribution = ((s - expected)**2/expected).sum(axis=1).sum(axis=1)
</code>
Comment: The simplest case of a $2\times 2$ table also presents the most extreme difference between the two sums--and there it is obvious that using only the value in one cell will not produce a chi-squared distribution.  One is left suspecting there's a problem with your simulation.
Comment: I don't follow this. Can you paste in the simulation that motivates this question?
Comment: As it's currently written, the constraint is not being applied correctly. Only one cell is being generated randomly. For a 2x2 table under the null, two of the cells have to be generated randomly using the same probability of the outcome but conditioning on the observed sample size for each exposure, i.e. hold the sample size for that exposure constant. That is, you condition on the marginal totals of the rows or of the columns, but not both.
Comment: With the hypergeometric sampling, the calculated p(Y) of the simulated samples is the same as the true p(Y). That is the constraint. So the result is the same.
Comment: @RobertAlanGreevyJrPhD: Thanks for your hint. I played with the constraints and the distributions for the sampling. I can reproduce the wanted behavior only with a constraint for the rows and column sums with a hypergeometric distribution. If I constraint only on the row or column sum I can't produce the chi^2 distribution. However, this is the data generating process for independent variables like you suggest. Maybe, I will open another question herefore.
Comment: You may also need to calculate the expected values based on the observed data as you do with the Chi square test in practice. The code currently assumes the true expected values are known.
Comment: @RobertAlanGreevyJrPhD: Yes, I completely agree with your comment. I have done this for the case of two binominals: https://stats.stackexchange.com/questions/439155/chi-square-sample-distribution-by-mc-for-2x2-table-independence-test   I will do it also with the hypergeometric distribution.
Answer: A simple sanity test: With $k$ cells and $k-1$ df (degrees of freedom), say, there are $k$ different ways of leaving out one cell from the sum. Which do you choose?
Besides that, after leaving out one cell, the remaining $k-1$ cells will not, typically, represent independent random variables.


Usage of SVR in Non Stationary Time Series Forecasting

Question: Based on my knowledge of Support Vector Regression(SVR), One of the assumptions of SVR are

Independent Identical Distribution.

So the application of SVR in forecasting of non-stationary Time series makes sense? As the properties of non-stationary is in violation of the basic assumptions of SVR.
Answer: The condition of independent identical distributions (iid) refers to the $(x,y)$ data points. Independence means:
$$
p((x_i, y_i), (x_k, y_k)) = p((x_i, y_i)) p((x_k, y_k)),
$$
i.e. the sampling of $(x_i, y_i)$ doesn't give us any information about the sampling of $(x_k, y_k)$, given the distribution.
And the identical distribution part says, that $(x_i, y_i)$ and $(x_k, y_k)$ have been sampled from the same distribution.
On the other hand, the stationarity requirement in time series, where the $x_i$ are just consecutive integers, is referring to the mean and autocovariance of the $y$ values, requiring those to be constant. In particular, $y_i$ and $y_k$ can still be dependent, as long as this dependence doesn't change.
Thus, both non-stationary and stationary time series (usually) violate the iid requirement.
Comment: If it violates the assumptions, Then it doesn't make sense to use SVR for this problem. Is that understanding right?
Comment: You would have to describe how exactly you want to apply SVR.


How to debug curl? gnutls_handshake failed -unexpected TLS packet (OpenSSL)

Question: How can I debug curl error further when Apache error.log is not showing any?

(35) gnutls_handshake() failed: An unexpected TLS packet was received.

curl -v https://example.com
* Rebuilt URL to: https://example.com/
*   Trying 127.0.0.1...
* Connected to example.com(127.0.0.1) port 443 (#0)
* found 151 certificates in /etc/ssl/certs/ca-certificates.crt
* found 612 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* gnutls_handshake() failed: An unexpected TLS packet was received.
* Closing connection 0

Ubuntu 16.04, apache2 working with SSL.
UPDATE:

echo | openssl s_client -connect example.com:443

CONNECTED(00000003)
139626124003072:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../ssl/record/ssl3_record.c:252:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 5 bytes and written 176 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1531383152
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
    Extended master secret: no
---

UPDATE2 - SOLVED
Had a blank line in my chain file and RootCA was not properly installed on the server i run openssl command from.
Comment: Try with `openssl s_client`. What does it say? TLS errors come before HTTP stuff so it can not necessarily show in Apache logfiles, and TLS errors are notoriously cryptic to debug. Alternatively, launch a network sniffer like wireshark. Anything special for your website? Static pages? Some application? What are your Apache TLS configuration directives? Did you try changing them?
Comment: Are you sure that the port 443 is a ssl encrypted port ? Not a non encrypted one ?
Comment: Thanks. I'm running Drupal 7 which works fine with **https** so I thought all was good but I ran `echo | openssl s_client -connect example.com:443` (see Update above) which now I think looks like certificates are not being sent properly?

Checking my configuration now.
Comment: Should have added that it mentioned **depth=1** which I understand is the 2nd cert being the intermediate one causing troubles from my chain file, which is strange as it's the same as in my other server config where it's working just fine. Bit stuck here.
Comment: Figured it out, RootCA was not properly installed, working now.
Comment: If you've solved this yourself, please write an answer and mark it as accepted. Without it, people will still think you need help.
Comment: Sorry I had updated my question but will post the answer shortly as well, thanks
Answer: I had a blank line in my chain file and RootCA was not properly installed on the server that I run the openssl command from. Once fixed curl working fine.
Comment: For future reference, when you see *New, (NONE), Cipher is (NONE)* in `openssl` output it means, despite that it says TLSv1.2 few lines below, that TLS handshake was **not** successful for whatever client or server or both sides problem.


How to convert the dictionary containing keys and list of list value?

Question:
How to convert the dictionary containing keys and list of list values to dictionary containing keys and list, drop duplicated in the newly created list ?
I tried running the following function and the computer got an 'memory error'

from collections import defaultdict

my_dict = defaultdict(list)
for k, v in zip(df_Group.guest_group, df_Group.list_guest):
  for item in v:
    v.append(item)
  my_dict[k].append(set(v))

My origin dictionary created from 2 columns of one dataframe like: {Group1: [[1,2,3,4], [1, 2, 5, 6 ]]}
I want my dictionary like : {Group1: [1,2,3,4,5,6]}
Answer: From what I understood, what you essentially want to do is flatten your list while keeping unique items.
The unique items can be achieved by converting the list into set and then back to list.
The unpacking part is really well explained in this post. Here's a working code for you -
df_dict = {
    'Group1': [[1,2,3,4], [1, 2, 5, 6 ]],
    'Group2': [[1,2], [2,3],[2,3,4]]
}

final_dict = {}

for k, v in df_dict.items():
    # flatten the list using double list comprehension
    flat_list = [item for sublist in v for item in sublist]
    final_dict[k] = list(set(flat_list))

This gives the final_dict as -
{'Group1': [1, 2, 3, 4, 5, 6], 'Group2': [1, 2, 3, 4]}

Please tell me if this answers your query.
Edit for Integer values in between the lists -
If we have a list with integer values in between, then you will get the int object not iterable error, to solve it we can check the instance to be int and make the item list by ourselves
Working code -
df_dict = {
    'Group1': [[1,2,3,4], 3, [1, 2, 5, 6 ]],
    'Group2': [[1,2], [2,3],[2,3,4]],
}

final_dict = {}

for k, v in df_dict.items():
    # making a new list
    new_list = []
    for item in v:
        # for int we will convert it to 1 length list
        if isinstance(item, int):
            item = [item]
        for ele in item:
            new_list.append(ele)
    final_dict[k] = list(set(new_list))

final_dict

Final dict -
{'Group1': [1, 2, 3, 4, 5, 6], 'Group2': [1, 2, 3, 4]}

As expected
Comment: Thanks for your help. I have tried this way, but got error  'int' object is not iterable' and cant solve with range(len(v))
Comment: If you used the dictionary that I have given in the code, then you shouldn't get that error. Can I know what type of dictionary are you using?
Comment: I have added an edit for your problem, tell me if this solves your problem.
Comment: My dictionary type is 'defaultdict' with value type is 'defaultdict object of collections module'. When I print dict,  its like:  'defaultdict(, {'Group1': [[170323, 38785, 43158, ...], [170323, 38785, 43158...]], 'Group2':[[42276, 67349, 56879,...], [422763, 673490, 588879,...],...]]})
Comment: Thanks for your effort, but still get error ' 'int' object is not iterable'. This dictionary contains all keys and values of 2 columns in a dataframe, which keys is 'group_name' and values is 'list of guest_id'.
Comment: If I use this way, dictionary will not contain all NON-duplicated values. Each group (keys) only contains a certain amount of equal value is 11 list_guest_id) !
Comment: I am not sure I understand you well,    "not contain all NON-duplicated values" do you mean It doesn't have the values that appear in more than one list (in a single group)? then I think you are mistaken.  In the above example, 4 is a NON-duplicated value and it appears in the final answer.
Comment: I dont know...it seems like the list_guest_id that are not duplicated with previous ids will be replaced when they have same 1 group_name (keys) and same length list_id_guest (11 id).
Comment: Can you provide me the data too? Without it whatever I answer you it would seem vague or won't work to you.
Comment: When i create dictionary with dict type 'defaultdict' for 2 columns . My dictionary have total 284 group_name, with each group containing 19 to 152 list_id and the same length list of 11 ids. For each row in dataframe, each group_name will change the list of ids in it, but the list length remains the same.


Why every polynomial over the algebraic numbers $F$ splits over $F$?

Question: I read that if $F$ is the field of algebraic numbers over $\mathbb{Q}$, then every polynomial in $F[x]$ splits over $F$. That's awesome! Nevertheless, I don't fully understand why it is true. Can you throw some ideas about why this is true?
Comment: The question is why the field of algebraic numbers is algebraically closed.
Comment: More or less, but not quite. This is saying that every polynomial in $F[X]$ factors over $F$.
Comment: Isn't that more or less the definition of [algebraic numbers](http://en.wikipedia.org/wiki/Algebraic_number)?
Comment: Thank you. I was reading that every polynomial in $\mathbb{Q}[x]$ splits over $F$ ;-)
Comment: In my opinion, you should add that it is the field of all algebraic numbers, in case of misread, thanks.
Comment: This is the transitivity of algebraic extension. If $L$ is an algebraic extension of $K$ and $K$ is an algebraic extension of $F$ then $L$ is also an algebraic extension of $F$. Here we use $F = \mathbb{Q}$.
Answer: The fact you mention is that the field $\overline{\mathbb{Q}}$ of algebraic numbers is algebraically closed.  This is true because it is the algebraic closure of the field $\mathbb{Q}$ inside the larger algebraically closed field $\mathbb{C}$, i.e., the set of all complex numbers which satisfy some nonzero polynomial equation with $\mathbb{Q}$-coefficients.
Notwithstanding the terminology, that the algebraic closure of a field in an algebraically closed field is algebraically closed requires (nontrivial) proof!  See for instance $\S 4$ of my notes on field theory, especially Proposition 17 and Corollary 18.
Answer: Consider some polynomial $$x^n = \sum_{i=0}^{n-1} c_i x^i,$$ where the $c_i$ are algebraic numbers. Thus for each $i$ we have a similar identity $$c_i^{n_i} = \sum_{j=0}^{n_i-1} d_{i,j} c_i^j,$$ where this time the $d_{i,j}$ are rationals.
Suppose that $\alpha$ is a root of the original polynomial. By using the above identities, every power of $\alpha$ can be expressed as a linear combination with rational coefficients of terms of the form $$\alpha^m c_0^{m_0} \cdots c_{n-1}^{m_{n-1}},$$ where $$0 \leq m < n \text{ and } 0 \leq m_i < n_i.$$ Putting all these $N = nn_0\cdots n_{n-1}$ elements into a vector $v$, we get that there are rational vectors $u_k$ such that $$\alpha^k = \langle u_k,v \rangle.$$ Among the first $N+1$ vectors $u_k$ there must be some non-trivial rational linear combination that vanishes: $$\sum_{k=0}^N t_k u_k = 0.$$ Therefore $$\sum_{k=0}^N t_k \alpha^k = 0,$$ and so $\alpha$ is also algebraic.
This proof is taken from these lecture notes, but it's pretty standard.


how to email output from measure-command

Question: I'm looking for a way to email the output from the measure-command command.
I have a script that runs the vmfs.unmap command and I would like to use measure-command to tell us how long it took and then email us the results once completed.
So far, I have:
Measure-Command {.\VMware_vmfsunmap.ps1}
which outputs:

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 11
Milliseconds      : 913
Ticks             : 119139896
TotalDays         : 0.000137893398148148
TotalHours        : 0.00330944155555556
TotalMinutes      : 0.198566493333333
TotalSeconds      : 11.9139896
TotalMilliseconds : 11913.9896

I can't figure out how to get the output into a email.
I have tried piping this into the send-mailmessage but it didn't work.
I can output it into an txt file using Out-File but then I'm not sure how to add that text to the body of an email.
I tried adding in a variable that says
$body = c:\scripts\output.txt

then
Send-MailMessage -From "vmfsunmap" -To "ME" -Subject "test vmfs unmap email" -Body **$Body** -SmtpServer smtpserver.com

but this just opened the txt file and didn't attach it into the body.
Does anybody have any suggestions?
Comment: i forgot to add that my powershell skills are very limited and im just learning this stuff... im sure im missing something basic but i dont know what!
Comment: ive also tried outputting to a txt file and then attaching the .txt file but that doesnt seem to work either.. theres no attachment in the email!

Send-MailMessage -From "vmfsunmap" -To "ME" -Subject "test vmfs unmap email" -Body "unmap completed successfully" -Attachments "txtfile.txt" -SmtpServer smtpserver.com
Answer: I believe the Body-parameter has to be a string so try piping the output to Out-String and see if that works for ya.
Measure-Command {.\VMware_vmfsunmap.ps1} | Out-String

The difference could be verified with something like this;
(Measure-Command {.\VMware_vmfsunmap.ps1} | Out-String).GetType().FullName

Should output System.String
(Measure-Command {.\VMware_vmfsunmap.ps1}).GetType().FullName

Should output System.TimeSpan
Comment: `$body = Measure-Command {.\VMware_vmfsunmap.ps1} | Out-String` then use $body in your Send-MailMessage
Comment: oh ok.. that makes more sense now.. ok ill try it out


Failed to instantiate module myApp due to: Error: [$injector:nomod]

Question: I am having an error on this code. I don't know why I am using angularjs 1.7.x version
$(document).ready(function () {
    $('#signupBtn-spinner').hide();

    var app = angular.module('myApp', []);
    $('#signupBtn').click(signup);
    function signup() {
        app.controller('signupController', ['$scope', '$http', function ($scope, $http) {
            alert('hello')
        }]);
    }
})

Answer: I strongly recommend you to avoid to use jquery with Angular/js
If you want to implement signup/login logic, suggest you to use ui-router. Some example.
Also please read this great Josh David Miller's answer "Thinking in AngularJS" if I have a jQuery background

About your problem:
You get this error from ng-app.
Put var app = angular.module('myApp', []); out of $(document).ready
Angularjs is loaded and it does not see any module because it is still not ready.

var app = angular.module('myApp', []);

$(document).ready(function () {
    $('#signupBtn-spinner').hide();

    $('#signupBtn').click(signup);
    function signup() {
        app.controller('signupController', ['$scope', '$http', function ($scope, $http) {
            alert('hello')
        }]);
    }
})


Run a command-line file that has output, but bypass that and allow me to continue running commands

Question: I'm trying to run some php files that have output and can take up to an hour to run, but I don't need to see the output as its writing to a log file (or I can push output to a log file) and I want to be able to run commands while its running (I don't care to be notified in any way that it's done; I can just go check the log file). How would I do this?
Comment: You don't tell us what operating system you're running. Such information would be important...
Comment: Sorry, it's Linux. They all behave the same way that I've ever seen on any of them in regards to this issue though. I type a command, it sits there outputting while I wait. I simply want to have it bring me back to the command line while it runs, whether it has output or not. Like, I want to funnel the output to /dev/null or something. I'm running CentOS 6.3 by the way.
Answer: Use a different ssh session or use a terminal multiplexer like GNU Screen or tmux.
Answer: Two ways to do this
command

ctrl-Z to interrupt
jobs

(list all jobs in your current shell, assuming there is only one)
bg

will take the top job in your queue and put it in the background
Or, just start it in the background from the beginning
command &

Any STDERR or STDOUT will show up on the screen so you will want to redirect those to a file
Comment: OK, I think this brings me closer. I don't know why you're the only one to understand my question or why this isn't a more asked-about issue. The admins closed this as not a real question yet you got it! Thanks.
Comment: np, if you need more help on this message me I guess if this is closed.  Good luck!


Python: How to count the number of moving average crossovers + highest point between each crossover?

Question: I am backtesting a simple moving average strategy, using price (for example daily bars) and a simple moving average. I want to find out how often the price crossed over or below the moving average over my historical data for stock X. In other words I want to find out the total number of crossovers.
I also want to find out the maximum / minimum point between each crossover. As price moves around the moving average it is sometimes above the average and sometimes below. I want to measure theese alterations. By this I mean the highest distance in ticks or percent between crossover A and crossover B, using crossover A as the baseline.
Please look at this picture to clarify what I mean:

I would appreciate any help that can point me in the right direction on how to code this in Python :-)
Comment: what have you tried so far?
Answer: As a first step, to calculate the number of crosses and when they occur, you can do
something like the below. Treat it as pseudocode to get an idea..
<code># MA: list containing the values of the moving average for each time period
# High: list containing the highs of each bar
# Low: list containing the lows of each bar
MA = [...]
High = [...]
Low = [...]
count = 0  # the number of crosses
index_cross = []  # the indices where crosses occur
for i in range(len(MA)):
    if Low[i] < MA[i] and High[i] > MA[i]:
        index_cross.append(i)
        count += 1
</code>
Now you have the number of crosses and when they occurred. This assumes that the bars cross the MA.
(i.e. there are no gaps, where the previous bar's low is above the MA and the current
bar's high is below the MA).
Then you can proceed by using the index_cross indices to find the maximum deviation of the price from where the cross happened. You have to consider if you will use closing prices or in the case of uptrends-highs and in the case of downtrends-lows..
As a side note, to annotate a graph with the points of interest, you can look into pandas (library for data analysis). Also such annotations tend to get quite messy when the markets are ranging.
Hope this gives some direction..


$\sum_{k=1}^{+ \infty} \frac{x^{k+1}}{ k (k+1)}= x + (1-x) \ln (1-x) $

Question: For $x \in ]0,1[$, we want to prove, without convergence theorem, that :
$$\sum_{k=1}^{+ \infty} \dfrac{x^{k+1}}{ k (k+1)}= x  + (1-x) \ln (1-x) $$

My attempt :
$
\begin{align*}
\sum_{k=1}^m \dfrac{x^k}{k}&= \sum_{k=1}^m \int_{0}^{x} t^{k-1} dt \\
&= \int_{0}^{x} \sum_{k=1}^m t^{k-1} dt \\
&=\int_{0}^{x} \dfrac{1- t^m}{1-t} dt \\
&= \int_{0}^{x} \dfrac{1}{1-t} dt - \int_{0}^{x} \dfrac{t^m}{1-t} dt \\
&= \ln(1-x) -  \int_{0}^{x} \dfrac{t^m}{1-t} dt \\
 \int_{0}^{x} \dfrac{t^m}{1-t} dt & \leq x^m \int_{0}^{x} \dfrac{t^m}{1-t} dt  \\
& = x^m \ln(1-x) \\
& \xrightarrow[ m \to  \infty ]{} 0 \\
\sum_{k=1}^{\infty} \dfrac{x^k}{k}&= - \ln(1-x)
\end{align*}
$
I integrate term by term , and how to justify it ?
Comment: [(1)](https://math.stackexchange.com/q/1457451), [(2)](https://math.stackexchange.com/q/1579815), [(3)](https://math.stackexchange.com/q/2836101), [(4)](https://math.stackexchange.com/q/3774182)... and a lot of posts with this as an intermediate result. (Just found [mine](https://math.stackexchange.com/q/2265258)...)
Answer: $$S=\sum_{k=1}^{+ \infty} \dfrac{x^{k+1}}{ k (k+1)}$$ $$= x + (1-x) \ln (1-x) $$
Use $$\sum_{k=1}^{\infty} \frac{x^k}{k}=-\ln(1-x)$$
$$S=\sum_{k=1}^{\infty} x^{k+1}\left( \frac{1}{k}-\frac{1}{k+1}\right)=x \sum_{k=1}^{\infty} \frac{x^k}{k}-\sum_{j=2}^{\infty} \frac{x^j}{j}.$$
$$S=-x\ln(1-x)+\ln(1-x)+x=x+(1-x)\ln(1-x)$$
Answer: $\int \sum_n f_n(x) dx=\sum_n \int f_n(x)$ if $f_n$ are non-negative continuous (or  measuarble ) functions. This is a special case of Tonelli's Theorem. It is also a consequence of Monotone Convergence Theorem.
Comment: Could we find a more elementary proof, and for example prove an uniform convergence ?
Answer: If $\sum_n f_n'(x) = g'(x)$ with uniform convergence and $\sum_n f_n(x_0) =g(x_0)$ for a particular $x_0$, then $\sum_n f_n(x) = g(x)$ with uniform convergence on compact sets.
The proof is something like $$\Big\lvert\sum_{n=0}^m f_n(x) - g(x)\Big\rvert \leq\Big\lvert\sum_{n=0}^m f_n(x_0) - g(x_0)\Big\rvert+\Big\lvert\int_{x_0}^x\sum_{n=0}^mf_n'(y)-g'(y)dy\Big\lvert \leq \varepsilon(1+\lvert x-x_0\rvert)\leq\varepsilon(1+M).$$
Now, $$\sum_{k=1}^\infty x^{k-1} = \frac1{1-x}$$ uniformly on compact subsets of $[0,1)$.
Since $\sum_{k=1}^\infty \frac{0^k}k = 0$, we obtain that $$\sum_{k=1}^\infty \frac{x^k}k = -\log(1-x).$$
We can now apply it again, since $\sum_{k=1}^\infty \frac{0^{k+1}}{k(k+1)} = 0$, and deduce that $$\sum_{k=1}^\infty \frac{x^{k+1}}{k(k+1)} = x + (1-x)\log(1-x).$$


Undefined index: cck_time_field_presave()

Question: I have imported about 2 thousand nodes that include start time.
I have imported and the formating and time looks the way it should.
Now if i try to publish the nodes i get following error -

Notice: Undefined index: hour in cck_time_field_presave() (line 97 of
  public_html/sites/all/modules/cck_time/cck_time.module).

The time fields gets changed to null time.
But if I open the node and save it - the node is saved with the correct time as it was before.
Im at a loss.
And hoping for some guidance.
Answer: Go to CCK Time then open cck_time.module
find this:
function cck_time_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items)

change this:
if (($items[0]['hour'] === '') || ($items[0]['minute'] === ''))

to this:
if ( empty($items[0]['hour']) || empty($items[0]['minute']) )

It helped solving my problem getting the same error Undefined index: cck_time_field_presave()


Converting GMT value for DateTimeZone?

Question: I'm currently using this to convert a timestamp to a user's defined timezone. My problem is that DateTimeZone() requires a timezone like Europe/Vienna or America/Chicago:
$date = new DateTime("@".$timestamp);
$date->setTimezone(new DateTimeZone("America/Chicago"));

I already looked into supported timezones on https://www.php.net/manual/en/timezones.php but there are so many of them and I don't want users to browse the whole list.
Is there a simple way converting e.g. GMT+1:00, GMT-4:30 or GMT+5:45 to a correct value for DateTimeZone().
Or is it better to use an array list like I found here: Convert selected time and timezone to a set timezone
Is it better to use UTC or GMT in general for the user to pick?
Thanks!
Comment: GMT-offset based values are ambiguous. A given offset often maps to several timezones.  A given offset may become incorrect for the use when their daylight savings boundary is crossed.
Answer: I don't think there's another way to pass a timezone. I think the time zones used in PHP have to be location-based to determine the DST settings along with the offset.
However, you can still present the options as GMT+1:00 etc to your users. And you can narrow down the list to only the much-used options (UTC, GMT, PST, etc).
Answer: You should probably obtain the user's real timezone (selected from the complete list). Using only a static offset from UTC you will not be able to follow the correct daylight savings time rules for the user's location.
PHP's DateTimeZone doesn't appear to accept POSIX timezone strings so it looks like you're stuck with predefined timezones.
Look in /usr/share/zoneinfo/Etc. There are a bunch of timezones predefined there for UTC plus and minus an integer. The only gotcha is that the sense of + and - is reversed from the normal convention. So just use, for example, "Etc/GMT-9" for a generic timezone with offset +0900.
This doesn't handle all of the possible timezones, like Nepal's weird +0545 but it looks like it's the best option that's easily accessible.

Converting GMT value for DateTimeZone?