How to differentiate between colors for the keywords "import" "def" and "try" in emacs?

Question: I am new to emacs. I have started using the twilight theme for emacs from here. But I get the same color for import def class try and if in python.(I have only tried python with this theme so far.)
However, I want a different set of colors for the following pairs:

import and from
def and class
try and if.

I looked into the theme file and have figured out that the font-lock-keyword-face determines the color of the above keywords and those similar to them.
So how can I set different colors to the above pairs? Is there a way?
I am on emacs24. Whats wrong with my .emacs?
Comment: It's not the issue of the color theme. `python-mode` classifies all these words syntactically
as keywords. That's why they all have the same face and always will, until someone rewrites `python-mode`.
But I really like it the way it is now. There is a workaround to add your own regexp highlighting,
but that harms the editor responsiveness.
Comment: Also it's not good to ask two unrelated questions at once.
Comment: Yes, please split that second question into a second question (if you cannot find a duplicate with the search).
Comment: @abo-abo Thanks for that. But I looked up the same theme on sublime. `import` `class` and `try` have different colors. Whereas in vim, on a different theme, the colors for `import` and `class` are different.
Comment: And yes I will split it up now.
Comment: split the question. heres the new one: http://stackoverflow.com/questions/19374683/how-to-fix-symbols-function-definition-is-void-while-loading-up-a-color-theme
Answer: Because ALL of the following keywords are defined within python.el as python-font-lock-keywords, you would need to trump some of them with a different font face or hack the source for these same keywords to have different font faces:
"and" "del" "from" "not" "while" "as" "elif" "global" "or" "with" "assert" "else" "if" "pass" "yield" "break" "except" "import" "class" "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda" "try" "print" "exec" "nonlocal" "self".
The following code is an example of how to trump python-font-lock-keywords for some of the keywords that have already been defined within python.el -- in this example, while is blue with bold; and, for is green with bold and italics.   python-font-lock-keywords that are not trumped by specially defined font faces will default to font-lock-keyword-face -- I have included a sample modification of that face as well:
(custom-set-faces
  '(font-lock-keyword-face
     ((t (:background "white" :foreground "red" :bold t))))
  )

(defvar lawlist-blue (make-face 'lawlist-blue))
(set-face-attribute 'lawlist-blue nil
  :background "white" :foreground "blue" :bold t)

(defvar lawlist-green (make-face 'lawlist-green))
(set-face-attribute 'lawlist-green nil
  :background "white" :foreground "green" :bold t :italic t)

(defvar lawlist-keywords-01
  (concat "\\b\\(?:"
    (regexp-opt (list "hello" "world" "while" ))
  "\\)\\b"))

(defvar lawlist-keywords-02
  (concat "\\b\\(?:"
    (regexp-opt (list "foo" "bar" "for" ))
  "\\)\\b"))

(font-lock-add-keywords 'python-mode (list

  (list (concat
    "\\("lawlist-keywords-01"\\)") 1 'lawlist-blue t)

  (list (concat
    "\\("lawlist-keywords-02"\\)") 1 'lawlist-green t)

   ))

Comment: Yes, the entire code gets inserted into the `.emacs` file -- go ahead and give it a try.  It's bedtime here now and I'll check back tomorrow to see if you have any follow-up questions.  It should work without any problems.
Comment: I think Im doing something wrong. Put the entire code in `.emacs` and added this `'(lawlist-keywords-01 ((t (:foreground "#000000"))))` to the `color-theme-twilight.el`. Not working. :(
Comment: The code in this answer was designed to be used inside the `.emacs` file.  Try it first without any modifications (e.g., by placing the entire code at the bottom of your `.emacs` file), and then restart Emacs, and then open up a python script and try using `while` and `for` to see the effect.  The code in this answer was **not** intended to be a modification of `color-theme-twilight.el`.  I just double checked my code and it works correctly.
Comment: I did that. Also I read that there should be only one instance of custom-set-faces. I have ensured there is only one. But it's still not working for some reason.
Comment: Based on this question / answer, and your other thread, it sounds like your Emacs installation has problems.  I would suggest backing it up somewhere and installing a new current version of Emacs -- i.e., start fresh.  Back-up and then delete or rename your `.emacs.d` folder also.  The code here should work -- if it doesn't work, then something is likely wrong with your Emacs installation.  If you are using a starter kit, then that may also be causing problems.
Answer: There's nothing wrong with your .emacs. That's what font lock does: there's a handful of font lock targets--one for types, one for variables, one for keywords, etc. You can customize what face each one gets (e.g., M-x customize, then Faces, Font Lock, Font Lock Faces), and you can configure how each language matches regular expressions to targets. Since those are all keywords, they all get mapped to the keyword face.
If you really want to, you can edit the font-lock-keywords variable set by python-mode to match each keyword separately, and instead of just naming a font-lock target as your facespec, give a list (face FACE PROP VALUE ...), with as many props and values as you prefer. If you really want to do this, you really want to read the docs.
The full details are described in the manual section "Search-based Fontification" (23.6.2 in GNU emacs 23.4; maybe different in your version, but you can find it pretty easily from the Font Lock customize page).
Comment: How come vim distinguishes between `class` and `import` keywords?
Answer: It's implemented here:
https://github.com/pdee/pdee
Code-base is basically that of python-mode.el, but comes with inlined Pymacs, company-mode, auto-completion
Or get it via bazaar:
bzr branch lp:python-mode/components-python-mode

which is the development-branch of python-mode.el


compare neighbourhood value with the mean value across all neighbourhoods in the city

Question: I have a dataset with all neighbourhoods in a city and their poverty rates. I would like to be able to create a vizualization that enables the user to select individual neighbourhoods and find out whether the poverty rate of that neighbourhood is significantly higher or lower than the city average across all neighbourhoods.
I am not sure what test to apply to achieve this.
Thank you very much!
Comment: Do you know how the poverty rate is defined in your specific data?  Also, do you have values of the denominators (total population in the neighborhood) for these rates?  And is the threshold for poverty rate the same across all neighborhoods, or does it differ by neighborhood (depending on what the median income in each neighborhood is, for example)?
Comment: Hi Alex, Thank you so much for your answer. The poverty rate is from census, it is just a percentage of people under an income threshold out of the total population in the neighbourhood. Thanks!
Answer: You need to obtain the population counts in each neighborhood that were used as denominators in computing these poverty rates, for two reasons:

If population counts and poverty rates are very different across neighborhoods, then taking an average of rates can produce very different results than computing one rate for the entire city.  For example, if one neighborhood has 500 people with 10 living in poverty, while another has 100 people with 20 living in poverty, the average rate will be (2% + 20%)/2 = 11%, but a combined rate will be (10+20)/(500+100) = 5%.
Parametric statistical tests (t-tests, chi-square tests, etc.) require sample size for deriving a test statistic and computing a p-value. Or in the case of exact tests of goodness-of-fit, when there is no test statistic, counts are still needed for calculating the probability of obtaining the observed data under the null hypothesis.

If you are able to get those counts, you might possibly be able to use the Binomial Test, which answers the question "if the true proportion is X%, what is the chance in Y number of trials that you'll observe a higher or lower number of events?"  I say "possibly" because this test is built on the assumption that observations are independent (in your case, that one person's outcome is independent of another person's outcome in the same neighborhood), which may or may not be valid with poverty (persons living in the same household would not be independent).
In your case, each person living in the neighborhood you are interested in would be considered one "trial", and each person living in poverty would be considered an "event".  The expected number of events would be the number of people living in poverty in this neighborhood if the rate matched the rest of the city, the "true" proportion ("X" above) would be the combined poverty rate for all other neighborhoods, and the observed number of events ("Y" above) would be the actual number of people living in poverty in your neighborhood of interest.
Binomial Test may not work in practice when there are large counts, because it requires calculating factorials of large values.  Instead, you can rely on the Likelihood Ratio test or Chi-Square Goodness-of-Fit test.  More info can be found here: http://www.biostathandbook.com/exactgof.html (on this page they use a different name for the Binomial Test: Exact test of goodness-of-fit).
Comment: I recommend that you modify the title or the wording of your question so it focuses specifically on the question of spatial correlation.  Based on a quick search, there is existing research on the goodness-of-fit tests in the realm of geospatial analysis.  See, e.g., https://onlinelibrary.wiley.com/doi/pdf/10.1111/j.1538-4632.1999.tb00973.x
Comment: Hi Alex, Thank you so much for your prompt and detailed message- that is very useful! I guess my main concern is regarding the spatial dependency of the neighbourhoods since they are contiguous polygons that compose the city, thus the observations (the neighbourhood values) are not independent, so I suspect I cannot apply classical statistics tests. I was thinking that I need to account for geography and for the potential spatial autocorrelation, so I am not sure what to do. Best regards!
Comment: Hi Alex, Thank you so much. I will mark this question as answered and reword, reframe my question and repost it. Thank you!


run-time error '713' - Application-defined or object-defined error

Question: Hi I have some software written in VB6.0 that uses an SQL Server, but I get this error:

Run-time error '713' - Application-defined or object-defined error

Does anyone know what causes this error?
Answer: This error, according to my own research, is not a vb6 error its actually a crystal reports error, it simply tells u that u need to go back to the developer machine, recreate the setup including all the dependencies and most importantly those for the crystal reports and you will be good to go
Answer: Is it related to this?
http://support.microsoft.com/default.aspx?scid=KB;EN-US;q248055
Might be missing a DLL?
Comment: this link is dead, what was the solution?


Filtering for Non-Nullable Strings in C# Lists

Question: I'm trying to create a list of non-nullable string values by filtering, but I always end up with a list of nullable strings.
var list = new List<string?> {"Cars", "Audi", "", "1920"};
var list2 = list.Where(p => !string.IsNullOrWhiteSpace(p)).ToList(); // return type is List<string?>

Can you help me understand why it doesn't return list of non-nullable strings.
Comment: It has nothing to do with being smart enough or not, this is about nullability semantics. As I mentioned below, nullability is independent to the values inside your collection.
Comment: I'm unsure of what you're asking. Are you asking for help on filtering or are you trying to understand what that does?
Comment: [This related question](https://stackoverflow.com/questions/59431558/using-linqs-where-select-to-filter-out-null-and-convert-the-type-to-non-nullabl) may be of interest. The nullability analysis isn't smart enough to do what you're expecting it to do.
Comment: @CharlesMager Well yeah, in addition to this possibility, I found now that it can be done also like this: list.Where(p => !string.IsNullOrWhiteSpace(p)).ToList()!;
Comment: @Blindy it's an area [the language team are looking to improve](https://github.com/dotnet/csharplang/blob/main/meetings/working-groups/nullability-improvements/NI-2022-11-01.md#linq). It could conceivably be tracked, as it is in non-linq scenarios.
Comment: You didn't understand the post you linked, it's talking about *selecting* data through an enumerable, which would obviously work. The OP however is constructing a list, which, as I mentioned, can still support null items to be later inserted. There are different semantics at play here.
Comment: @Blindy my understanding is fine, thanks. The selecting _doesn't_ work, there's a warning - that's the point. The proposed change is that nullability would be tracked and the `Where` would return a non-nullable contained type, as was the expectation in this question. The issue [linked at the top of the working group note](https://github.com/dotnet/roslyn/issues/37468) that prompted the discussion is exactly that. I don't see why you're hung up on it being a list at the end: Any list could have null items added to it later; that doesn't stop you creating a list of non-nullable types.
Answer: The type doesn't lose its nullability just because you decided to add only non-null items. After all, nothing is stopping you from adding nulls later.
If you want to change its type, either do it when creating the new list (ie, declare the variable explicitly as List<string>), or tell the compiler that the objects your filter returns are non-null:
list.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p!).ToList();

Comment: Now that I think about it, it makes perfect sense, thanks for answering!


Minimizing sum of functions implies minimizing their squares, maximizing the sum of the inverses?

Question: I have $n$ functions (Say $f_1\space to \space f_n$) of $k$ variables (Say $x_1\space to\space x_k$) each. The functions are all positive, as well as the variables $xi's$. I do not have explicit expressions for these functions. The objective is to minimize
$$\sum_{i=1}^n{f_i} \ \ \ \ \ \ \ subject \space to \ \ \ \ \sum_{i=1}^k{x_i^2} = P$$ where P is a known constant.
In which case(s) we can assume that this is equivalent to minimizing the sum of the squares of these functions ?i.e:$$min\sum_{i=1}^n{f_i^2} \ \ \ \ \ \ \ subject \space to \ \ \ \ \sum_{i=1}^k{x_i^2} = P$$
Also, in which case(s) we can assume that this is equivalent to MAXIMIZING the sum of the inverses of these functions ?i.e:$$max\sum_{i=1}^n{ {1\over f_i}}  \ \ \ \ \ \ \ subject \space to \ \ \ \ \sum_{i=1}^k{x_i^2} = P$$
Assuming that the functions are nicely behaved, continuous, differentiable and everything.
Comment: $n=1$, functions are constants or identical, feasible set is empty or a point, etc. In nontrivial situations values of $f_i$ should be distributed differently to produce optima.
Comment: Given that your constraint is non-convex, your convex optimization tag should be deleted.
Comment: Any thoughts on the answer I posted 2 days ago?
Comment: Are you still here?
Comment: yes sorry was out of town with no internet. This is not an answer, I know it is not the case most of the times that's why I am asking in which cases we can consider my assumption is true.
Answer: $x^{4/3}+y^{4/3}$ subject to $x^2+y^2=2$ is minimized at $(0,\sqrt2)$.
$x^{8/3}+y^{8/3}$ subject to $x^2+y^2=2$ is minimized at $(1,1)$.
So, in answer to the question in the title, minimizing the sum of functions does not necessarily minimize the sum of their squares.
Answer: All these cases are not equivalent. These are totally different target functions leading to a completly different optimization.


How to share an instance among several classes in c++, not using Singleton pattern

Question: Now I'm developing a c++ application and I'm facing a problem of sharing an instance.
For this problem, I created a simple class diagram. I want to share HogeDataManager for class A and C. A creates HogeDataManager and read HogeData via its public methods. And B adds some data to HogeDataManager.
For sharing HogeDataManager, I have to prepare set_mgr method for B and C. But I think it is not a smart way. Of course if I adopt Singleton pattern, it will be resolved. But Singleton is sometimes dangerous, so I want to find better ways to avoid such a problem.
Comment: _"For sharing HogeDataManager, I have to prepare set_mgr method"_ It's better to require this parameter in the constructors of these classes.
Comment: Is there any particular reason you avoid singleton?
Comment: You should revise the scenario of using `HogeDataManager`, its lifetime, possible number of instances, contexts, states. This will help you to make a better decision.
Answer: Your design is good:
A creates HogeDataManager, and takes it over to B, and B to C.
only missing yet the decision, which Object A, B or C has the responsibility, to destruct HogeDataManager finally.
If you deside, that A must create and destruct HogeDataManager, then you need a unset_mgr() in B and C.


Practicing Jazz on Alto Saxophone

Question: A little bit of background: I have been playing alto saxophone for about 15 years now and played in various bands. When I started, I had weekly appointments with a teacher and that was absolutely cool. I learned the basic stuff there and I was interested in playing jazz. The last 10 years I am playing a lot of jazz and I have played in a few big bands. I am completely familiar with all basic (minor, major) scales and a few different scales and I am pretty familiar with improvising. So far, so good.
Currently, I am a student and a long time I was in doubt whether I should go for a BSc in music or not, but I decided not to go for that option. However, I still feel the need to practice music. What books are absolutely must-reads both from a theoretical and practical point of view about jazz and (alto) saxophones? How can I improve my technique without going to a teacher (since I don't have the money and time currently for it)?
Comment: Given that, two school jazz bands later, I've never read or been given recommendations to read any jazz books that didn't consist of mostly elementary sheet music, I doubt that there are any "absolute must-reads". Then again, I played piano in school jazz bands, so....
Answer: The best way to get better is by playing jazz. This is especially true once you are past the fundamentals like scales as it sounds like you are.
Patterns
If you want to brush up and take that further I'd look into arpeggios and "patterns" (link) (link) (link). That is, playing arpeggios and their extensions from and to various scale degrees, as well as other idiomatic melodic patterns. These can help generally with technique just as playing anything can but more importantly the idea is that getting these under your fingers will make them slip into your improvising. This same concept applies to stealing licks from your favorite records—it's about building your vocabulary.
Theory
You can also always dig deeper into the theory and various approaches to improvising. For instance if you aren't familiar with things like guide tones, target and approach notes, enclosures, sequences, etc, they will all help. You can usually always dig deeper into your harmonic approach as well. You said you know "major, minor, and a few different scales", so it sounds like maybe you could dig a bit deeper into modes.
As far as a theory books, maybe check out Mark Levine's "The Jazz Theory Book" and/or Bert Ligon's Jazz Theory Resources. Andy Jaffe's Jazz Harmony is decent too and quite a bit shorter. There are all kinds of other books that either get more advanced or dive into specific topics. No single book will get you everything but a general theory overview book is a good start.
Playing Tunes
But as much of possible of this should be done in the context of tunes. Get some fake books (ex. The Real Books or The New Real Books) if you don't have them already and start working through tunes. Play the head and then a few choruses of improv just like if you were performing the tune. Dig deeper into the changes of these tunes and analyze them. Try different scales, modes, superimposed arpeggios, and patterns, etc. The point being that you should work new things in but the bulk of your practice time should be put toward actually doing what you're practicing for ... playing jazz.
Accompaniment
Jamey Aebersold's Play-Alongs are great for all this because they are focused around playing some tunes, have accompanying backing tracks, and include a book that gives you some things to work on within the tunes.
But something like Band-in-Box that can play whatever changes you put in is really useful either way.
Alto-specific
I don't think there's much alto-specific advice because the concepts are largely the same for all instruments with the exception that you don't have to worry about about playing chords like a piano or guitar player would. Though it's pretty common for students of any instrument, it may be particularly salient for an alto player to study the work of Charlie Parker. Even his heads are a good melodic exercise and embody the bebop sound. And because so many other musicians were inspired by him and studied him, it serves as a bit of a prerequisite to most of the jazz that came after. "The Omnibook" is worth picking up.
Listen
And of course, always be listening to jazz. Try transcribing things you like. Then study them, alter them, an work them into your solos.
Comment: Thank you for the extensive answer! This should keep me running for the next few months :-)

Practicing Jazz on Alto Saxophone


Possible to place a chord diagram summary before the music notation in MusicXML or MuseScore?

Question: Is it possible to place a chord diagram summary (fretboard legend) before the score music in MusicXML or MuseScore? If yes, then how?
Background:
The chord diagram summary (i.e. fretboard legend) would include all the chords used in the piece in a single table. These chords would not be associated with any musical measures in the piece.
And, thus the music measures could just show the chord letters. This helps the overall music be more compact and facilitates a quicks review of the chords used.
Here is an example...

At this time, the information that I've found in MuseScore is only for associating a Fretboard Diagram with a note in a measure.
Also, the MusicXML Chord Symbols example also only shows the Fretboard Diagram by assigned notes.
So, is either MuseScore or MusicXML capable of having a chord diagram summary before and not assigned to the music note/measure notation itself? If yes, how?
Comment: In MuseScore, you can select elements and drag them around the score. Have you tried attaching a fretboard diagram to a note and then moving it to the top of the score? You can also use horizontal lines to help with alignment (just make them white afterwards).
Comment: After you've printed the page into a PDF or other visual file for reading, does it cause some kind of a problem that the fretboard diagrams used to be technically associated with a note or rest in a measure in the MuseScore application? The idea is to produce written documentation for humans to interpret, isn't it. :)
Answer: First create fretboard diagrams for the chords in the first bar, and then drag the diagrams where you want them to be on your page.

Then add labels for them, for example as chord symbols. Select a note or rest and press Cmd-K (maybe Ctrl-K on Windows), type the chord's name and drag it where you want.

This is MuseScore 2.x. It might be different in 3.x.


SVG Sepia filter effect: mid-tones only

Question: Could you please help me finding out how can I achieve the Sepia tone on the link bellow using SVG?
My Sepia Tone made with Photoshop's Color Balance
I've tried the following code:
<svg class="defs-only">
  <filter id="monochrome" color-interpolation-filters="sRGB"
          x="0" y="0" height="100%" width="100%">
    <feColorMatrix type="matrix"
      values="1.00 0 0 0  0
              0.80 0 0 0  0
              0.65 0 0 0  0
                0  0 0 1  0" />
  </filter>
</svg>

CSS:
img{
    -webkit-filter: url(#monochrome);
    filter:  url(#monochrome);
}

But the feColorMatrix Sepia Tone that I get is very different and appears not to be only affecting the mid tones as it does on Photoshop.
Note: I can't use canvas.
Comment: What UA are you using here?
Comment: I'm using Google Chrome as a User Agent.
Answer: Well first of all, that's not a proper sepia filter. It's only using the red channel as input, so you're losing about a third of your luminosity off the bat. The "official" W3C sepia filter is:
   <feColorMatrix type="matrix"
  values="0.39 0.769 0.189 0  0
          0.349 0.686 0.168 0  0
          0.272 0.534 0.131 0  0
            0  0 0 1  0" />

That gives you this result:

And if you just want to process the mid-tones then you need to pull the mid-tones out and process them separately. That looks like this:
<filter id="mid-sepia" color-interpolation-filters="sRGB">
  <feColorMatrix type="luminanceToAlpha"/>
  <feComponentTransfer >
    <feFuncA type="table" tableValues="0 .2 0.5 1 1 1 0.5 .2 0"/>
  </feComponentTransfer>
 <feComposite operator="in" in="SourceGraphic"/>
   <feColorMatrix type="matrix" result="sepia-clip"
  values="0.39 0.769 0.189 0  0
          0.349 0.686 0.168 0  0
          0.272 0.534 0.131 0  0
            0  0 0 1  0" />

  <feColorMatrix in="SourceGraphic" type="matrix" result="gscale"
                values="0.2126 0.7152 0.0722 0 0
                        0.2126 0.7152 0.0722 0 0
                        0.2126 0.7152 0.0722 0 0
                        0 0 0 1 0" />
  <feComposite operator="over" in="sepia-clip" in2="gscale"/>
</filter>

And gives you something that looks like this:

The magic here is the settings for feFuncA - which controls how wide the mid-tone selection is. "0 .2 0.5 1 1 1 0.5 .2 0" is a pretty wide selection - so if you want a narrower range given the sepia treatment, you might want to use something like "0 0 0 0.2 0.5 1 0.5 0.2 0 0 0" - play with it until you have something you like.
http://codepen.io/mullany/pen/rjdYre?editors=1000#
Answer: I don't know if you see this, but a feColorMatrix generator exists : https://codepen.io/mullany/pen/qJCDk
You just have to change the image by yours :
<image x="0" y="0" width="590" height="400" filter="url(#f1)" xlink:href="[YOUR IMAGE]"/>

You can play with all the parameters like in Photoshop.
Enjoy (ノ≧∀≦)ノ
Comment: The problem is that the color change made by feColorMatrix is applied to all tones...No just the mid tones like Photoshop as I stated inicially.
Comment: It's maybe due to the fact the web colors are limited.

SVG Sepia filter effect: mid-tones only


compact sets and continuity

Question: Let be $X\subset \mathbb{R^m}$, $K\subset \mathbb{R^n}$ compact, $f : X\times K \rightarrow \mathbb{R^p}$ continuous and $c\in \mathbb{R^p}$. Suppose that for every $x\in X$, there is a unique $y \in K$ such that $f(x,y)=c$. Prove that the $y$ depends continuously from $x$.
-My idea was to take a function such that: $\varphi : X\rightarrow K$ where
$$\varphi (x) = y$$ then you should to prove that  $\varphi$ is continuous.
Thank you for your help.
Answer: Let $\varphi:X\to K$ be the function that you mentioned above. Let $x\in X$ and $(x_n)_{n\in\mathbb N}$ be a sequence with $x_n\to x$. Let $y_n := \varphi(x_n)$. Assume that $y_n \not\to \varphi(x)$. Then, by compactness there exists a subsequence $(y_{n_j})_{j\in\mathbb N}$ with $y_{n_j}\to z \neq \varphi(x)$.
Since $f$ is continuous $\displaystyle c = \lim_{j\to\infty}f(x_{n_j},y_{n_j}) = f(\lim_{j\to\infty}x_{n_j},\lim_{j\to\infty}y_{n_j}) = f(x,z)$.
Hence $z = \varphi(x)$. Contradiction.
Comment: Excuse me, but I don't understand why do you assume that $(x_n)$ converge to x? I don't have information about $X$
Comment: Because i am showing sequential continuity which is equivalent to continuity in metric spaces. That should be a familiar concept.
Answer: Sketch: There's nothing to prove at isolated points of $X$. Let $x$ be an arbitrary limit point of $X$, let $(x_{k})$ be an arbitrary sequence in $X\setminus\{x\}$ converging to $x$, and put $y_{k} = \varphi(x_{k})$ (using your definition of $\varphi$).
You know $K$ is compact, $f(x_{k}, y_{k}) = c$ for all $k$, and $y_{k}$ is the unique element of $K$ satisfying $f(x_{k}, y_{k}) = c$. Use these facts to show successively that:

$(y_{k})$ has a subsequence that converges in $K$.
Every subsequence of $(y_{k})$ that converges in $K$ has the same limit.
$(y_{k})$ itself converges in $K$.

Why does this finish the job?
Comment: So this sequence is constant, right? regards.
Comment: The sequence $(y_{k})$ is the set of values $\bigl(\varphi(x_{k})\bigr)$; generally, this sequence is not constant. (The "uniqueness" in my post referred to _for each $k$ there is a unique $y_{k}$_, but as $k$ varies, $y_{k}$ does, too.) Incidentally, have you made a sketch of the set-up of the problem? That will surely help you visualize and organize the proof. :)
Comment: Thank you sir, but you say the $y_k$ is the unique element of K after you say $f(x_k,y_k)=c$ for all $k$?. I'm confused :(
Comment: In other words, for _each_ $k$, $f(x_{k}, y_{k}) = c$, and if $f(x_{k}, y) = c$, then $y = y_{k}$. :)

compact sets and continuity


How to get all the forms inside my app

Question: I need to get  all the forms inside my c# application and add the .Text parameter for each one to a combobox control and i need to do all in one method (void)
myCode:
System.Reflection.Assembly[] assembly = AppDomain.CurrentDomain.GetAssemblies();
foreach(System.Reflection.Assembly asem in assembly)
{
    foreach(Type t in asem.GetTypes())
    {
        ComboBox1.Items.Add(t.Name);
        //here i need to get the .Text param
        //where Name is the Form name
    }
}

Comment: Which technology is this? WebForms? WinForms? WPF? ...?
Comment: Winforms technology.
Comment: Possible duplicate of [C# Get form names of project A from Project B](http://stackoverflow.com/questions/16118946/c-sharp-get-form-names-of-project-a-from-project-b)
Answer: You can use the Application.OpenForms property to get a list of all currently open forms.
You cannot iterate all the types since you don't get the running instances but only the types. If you don't have an instance of a class, the class does not exist in memory.
(Just because a class is instantiated does not mean that it has a visual appearance, even if the class derives from Form).
Comment: @the2xbeaast How would that be ever possible? If you don't have an instance, they do not exist in memory.
Comment: then how to call each one without write each one ? and doing it in a method.

How to get all the forms inside my app


how to : specify a default action for a TYPO3 v4.5.30 extbase extension?

Question: I made  a new extension in extension builder (a basic 4 model extension with no custom work in it, the only thing slightly fancy it does is extend the fe_users table) and installed it and made a page with the plugin and when I view the page I get a blank area where the plugin should appear - not a whole blank page just the part where the plugin should appear.  I put some echo __FUNCTION__.__LINE__;die; lines in all the listActions so if I was hitting any of them I'd at least know which I was hitting.  But I see no echo lines and I clearly never hit a die; so I guess my extension is not hitting any action, maybe because I have to specify one as the default. My extension has 4 models.  How do I specify what action gets called?  I am using typo3 v4.5.30 with extbase.
Thanks
PS: my ext_localconf file looks like so:
Tx_Extbase_Utility_Extension::configurePlugin(
    $_EXTKEY,
    'mycore',
    array(
        'Player' => 'list, show, new, create, edit, update, delete',
        'Hall' => 'list, show, new, create, edit, update, delete',
        'Hallplayers' => 'list, show, new, create, edit, update, delete',
        'Hallvisits' => 'list, show, new, create, edit, update, delete',

    ),
    // non-cacheable actions
    array(
        'Player' => 'create, update, delete',
        'Hall' => 'create, update, delete',
        'Hallplayers' => 'create, update, delete',
        'Hallvisits' => 'create, update, delete',

    )
);

Comment: did you add a plugin as well ? It allows you to choose proper order of actions like `YourController=>list,show,edit` and if you did that it should work out of the box
Comment: in the ext builder?  that stuff is in my ext_localconf file already. When I add it in the builder it just limits things and I get the same behavior.  I bet there is some simple little thing I am forgetting to do in ext builder.  what about the frontend plugin key - why can't I use the same as my ext key?
Comment: ok, had to do several things in ext builder:  add a frontend plugin for each model, add the controllable actions and non-cacheable actions for each, point my page to one of the new plugins and remove the priority option "top" under the "more options" section.  now it works.
Answer: To answer your initial question: The first action defined in your plugin is automatic the default action. I never use 2 Actioncontroller in 1 plugin (Im not sure if that is even possible). If I have to change from 1 actioncontroller to another I use Fluid-Link:
<f:link.action pluginName="myOtherPlugin" pageUid="ThePageIDwhereThePluginShallBeCalled" action="TheActionOfThePlugin" controller="Controllername" arguments="{Modelname : Modelobject}">


projeto react-native nao funciona no celular e nem no emulador comando react-native run-android ao ser executado aparece este erro abaixo

Question: Erros abaixos:
:\meuApp\smartMoney>react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 967 file(s) to forward-jetify. Using 4 workers...
info Starting JS server...
O sistema n�o pode encontrar o caminho especificado.
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of emulator -list-avds.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon, 1 incompatible and 1 stopped Daemons could not be reused, use --status for details
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings
FAILURE: Build failed with an exception.

What went wrong:
Task 'installDebug' not found in project ':app'.
Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Get more help at https://help.gradle.org

BUILD FAILED in 34s
error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
FAILURE: Build failed with an exception.

What went wrong:
Task 'installDebug' not found in project ':app'.
Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Get more help at https://help.gradle.org

BUILD FAILED in 34s
at makeError (C:\meuApp\smartMoney\node_modules\execa\index.js:174:9)
at C:\meuApp\smartMoney\node_modules\execa\index.js:278:16
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async runOnAllDevices (C:\meuApp\smartMoney\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:94:5)
at async Command.handleAction (C:\meuApp\smartMoney\node_modules\@react-native-community\cli\build\index.js:186:9)

por favor alguem me ajude estou a tres dias nao consigo resolverja instalei tudo denovo e nada
Answer: Certifique-se de que esteja fazendo tudo corretamente:
Primeiro faça o build no android-studio para verificar o projeto.
Depois vá ao seu terminal e na pasta do seu projeto entre na pasta android:

cd android

Após entrar, digite o seguinte comando

./gradlew installDebug

e aguarde.
Não esqueça de rodar a aplicação no android-studio anteriormente.
Comment: Ruan Duarte,  desculpe amigo mais sou novo nesse ambiente de desenvolvimento e estou no começo de tudo ainda nos estudo oque voce quer dizer com fazer "BUILD"?
Comment: Abre o android-studio e carregue seu projeto, automaticamente ele ira fazer o build, espere dar a resposta de sucesso e prossiga para o terminal
Comment: ixi parceiro nao deu certo o cmd nao reconhece este comando coloquei uma foto pra ver melhor os erros


Incluir hora com minuto em um array de horas javascript

Question: Tenho um método que gera um array de hora numero e hora string, um para mostrar na tabela e outro para mandar no json. A questão é que eu gostaria de incluir 01:00 / 01:30 - 02:00 assim por diante.
function listaHorasDia() {
    var horas= [];
    for (var h = scope.horaInicio; h < (scope.horaFinal +1); h++)
        horas.push({ horaNumero: h, horaExibicao: ('00' + h).substr(-2) });
    return horas;
}

Gostaria que meu array ficasse da seguinte forma
horas = [
{horaNumero:1330, horaExibicao: '01:30'},
{horaNumero:1400, horaExibicao: '14:00'}
]

e assim por diante
Comment: Poderia detalhar melhor o que você quer incluir?
Comment: editei a pergunta @FelipeAvelar
Comment: Mas você já recebe isso no scope? Ou você tá querendo que, dentro do for, o incremento seja de 30 em 30 minutos?
Comment: no scope eu recebo um numero inteiro, gostaria que dentro do for fosse feito isso @FelipeAvelar
Comment: Não seria o caso de só adicionar mais um `push` no for? No caso adicionaria esse push: `horas.push({ horaNumero: h+30, horaExibicao: h.toString().substr(-2)+':30' });`?
Comment: Nesse caso eu perco a hora inteira                                                                  `0: {horaNumero: 30, horaExibicao: "0:30"}
1: {horaNumero: 31, horaExibicao: "1:30"}
2: {horaNumero: 32, horaExibicao: "2:30"}
3: {horaNumero: 33, horaExibicao: "3:30"}`
Answer: Pelo que foi passado nos comentários, provavelmente isso resolve o seu problema:
function listaHorasDia() {
    var horas= [];
    for (var h = scope.horaInicio; h < (scope.horaFinal +1); h++) {
        horas.push({ horaNumero: h, horaExibicao: ('00' + h).substr(-2) });
        horas.push({ horaNumero: h+30, horaExibicao: h.toString().substr(-2) + ':30' });
    }
    return horas;
}


Drush error when running dmu-analyze to update drupal modules

Question: I'm using drupal module upgrader with drush to update the modules which are drupal 7 compatible at the moment. I'm getting this error when I try running drush dmu-analyze MODULE_NAME

I can't seem to find a solution on the net to fix this issue. I have tried re-installing the module or drush. Even when I type drush status I'm also getting this error.
Comment: In future please include error messages as text rather than screenshots, it makes them easier to search. Thanks!
Answer: One of the modules in your installation is incorrectly using references to services without quoting them.
e.g.
[@container.namespaces]

instead of the valid:
['@container.namespaces']

The error message doesn't provide enough details to be able to identify which module is causing the problem. It's going to be a contrib/custom one, though, so check the .services.yml file for the extra modules you have installed and you should find the culprit. It's likely to be under a service whose name begins with plugin.manager..


Wagtail admin: Linking to tabbed section via language formatted id

Question: I want to be able to go to a certain tab in the admin interface, but Im unsure how to go about it since Its language specific. I have this in my tabbed interface:
edit_handler = TabbedInterface(
    [
        ObjectList(content_panels, heading=_("Content")),
        ObjectList(form_content_panels, heading=_("Forms")),
        ObjectList(event_registration_panels, heading=_("Participants")),
        ObjectList(message_panels, heading=_("Messages")),
        ObjectList(promote_panels, heading=_("Promote")),
        ObjectList(TranslatablePage.settings_panels, heading=_("Settings")),
    ]
)

I now want to link directly to the messages tab for example. But the id for this is based on the gettext formatted heading, in swedish:

in english:

This makes it hard to link correctly. How can I supply a non-language formatted id?
Answer: Figured it out, Im a bit slow.
Of course, when creating the link I can use the same wording as when i create the heading, this creates the correct link.
tab_index_name = _("Participant").lower()


Editing user submission of user registration form with hook_user_insert() and $edit

Question: I recognize there is a similar question here:
drupal.stackexchange.com/questions/38124/hook-user-insert-get-form-values
but I've got Eclipse and XDebugger setup so I can see the variables and I am still stuck.
I provide the variables below, please note field_foo is a field the system has taken care of properly without my interfering, after the user submits it, field_bar is a field I want to change the submitted value of, it has the value 303031 when the system handles it from form submission, where the variables show "value 300501 " is my attempt to edit that value - clearly I'm editing something wrong)
$edit   Array [37]
[0...30]
    uid 63
    field_foo   Array [1]
        und Array [1]
            0   Array [1]
                value   asdasd
                    length  6
                    0   61
                    1   73
                    2   64
                    3   61
                    4   73
                    5   64
    field_bar   Array [2]
        und Array [1]
            0   Array [1]
                value   303031
        value   300501

Here is my code to try and set it...
function MY_MODULE_user_insert(&$edit, $account, $category) {

    $newBarValue = 300501;
    $edit[field_bar][value] = $newBarValue;

}

PLEASE NOTE:
I don't know if this is the case for all field_data_field Core fields but I had to use the following to get it to work:
$edit[field_bar][und][0][value] = $newBarValue;
This might be unique as I am working on someone else's work atm.
Answer: hook_user_insert() is invoked after the user object and all it's fields have already been committed to the database; that's why your code isn't taking effect at the moment.
There are a couple of ways you could go:

Use exactly the same logic in hook_user_presave(), which gets called before the data is committed to the database.
Implement hook_form_alter() for the registration form, add a custom validation function, and manipulate the field values in there.
Comment: Thanks, I used hook_user_presave() as for some reason hook_form_alter() was having no effect on the user registration form. Thanks a lot
Comment: Actually, that hasn't worked - hook_user_presave() certainly makes more sense, but I think it might be my array editing that is causing trouble atm. I will read up to see if for a field_data_field Core field I should be editing it in a different way. Any thoughts on that?
Comment: **PLEASE NOTE MY EXTRA BIT** when following this answer - the problem was I needed to use this: `$edit[field_bar][und][0][value] = $newBarValue;` to edit the correct part of the array


$K$ is a linear compact operator on Hilbert space $H$. Will the image of $I-K$ on every closed subspace of $H$ be also closed?

Question: Just as the title. We know the image of $I-K$ is closed, but if we restrict $H$ to a closed subspace $V$, will $(I-K)(V)$ be a closed subspace of $H$? Any hint is appreciated.
Answer: Hint: If $V\subset H$ is closed then, $I-K$ restricted to $V$, still being a proper map.
Comment: I'm sorry, but I don't understand what "still being a proper map" means in your hint.
Comment: @Martin, take a sequence $y_n=(I-K)x_n$ in $(I-K)(V)$ converging to some $y\in H$. Then the set $\{y_n\}_n\cup\{y\}$ is compact. Because $I-K$ restricted to $V$ is proper, you have that the set $\{x_n\}_n\cup\{(I-K)^{-1}{y}\}$ is compact.
Comment: I see. I was asking about the meaning of proper, but it is clear now. Thanks


How to visualize the pole-polar relationship if placing pole inside the conics?

Question: This problem comes from  R.Hartley & A.Zisserman Multiple View Geometry in Computer Vision at page 58:

To my understanding, the polar $l$ dipicted in above figure goes through two points at which tangent lines insect at pole x. The polar is tangent line when x is on the conic.
My question: How to visualize polar $l$ when x is inside the conic?
Comment: Why would you put $x$ inside the conic?
Comment: @DavidK : It may not occur in the real circumstance, but  I just seek the answer from a mathematical view.
Answer: Here is something I hope that can be useful
Comment: Great! I can get it more easily combining your figure with orangskid's strategy.
Answer: You simply do not visualize any such thing. There are no tangents to the conic from a point inside.
Answer: The pole-polar has the following important property: if point $x$ is on line $l$ then the polar of $x$ contains the pole of $l$.
So, to find the polar of a point inside, take two line passing through $x$, $l_1$ and $l_2$. Find the poles of those lines, $x_1$, and $x_2$. The line through $x_1$, $x_2$ is the polar of $x$.
Comment: Understandable and concise strategy. Thank you! :)
Comment: @Finley: No worries! And now you should also know how to find the pole of a line that does not cut the conic.
Comment: Yeah, take two points on the line, then find polars of these two points. Intersection of the two polars is the pole of this line. How fantastic the duality is!


put string and character in ofstream

Question: I want to put string and character together in ofstream() but I get error I want to create files in different names but in same path for example like this E://string.txt but string is variable
can you help me?
#include <iostream>
#include <ofstream>
using namespace std;
int main()
{
  string filename;
  ofstream note("E://"filename".txt",ios::app);
}

Can you get my point?
I know my code is wrong but help me fix it!
Answer: You can form your path with a stringstream, then extract a C-string out of that stream when you need it for constructing the ofstream:
std::stringstream path;
path << "E:/" << foo() << ".txt";

std::ofstream ofs(path.str().c_str());

If you only need to concatenate strings and characters, you can probably get by without the stream (which we've used above for its formatting features):
const std::string path = "E:/" + foo() + ".txt";
std::ofstream ofs(path.c_str());

In C++03, the ofstream constructor requires a C-string (.c_str()) for historical reasons, though this is fixed in C++11:
const std::string path = "E:/" + foo() + ".txt";
std::ofstream ofs(path);

Using your new example:
#include <iostream>
#include <fstream>
int main()
{
  string filename;
  ofstream note(("E:/" + filename + ".txt").c_str(), ios::app);
}

Comment: Change that to `` not ``. :)

put string and character in ofstream


Web Service PHP com INNER JOIN

Question: Estou criando API para consumo em aplicativos Ionic, mas estou penando à 2 semanas em uma dessas api's, onde eu relaciono dados em mais de uma tabela com inner join. Tentei fazer como no meu sistema php, onde eu adiciono os itens no banco, alguém poderia me ajudar a concluir essa api?
<?php header("Access-Control-Allow-Origin: *"); header('Content-Type: application/json; charset=utf-8');

$db = new mysqli("mysql.meudominio.com.br", "nome", "senha", "nome");

$sql = $db->query("SELECT refeicao.nome, refeicao.id FROM refeicao_refeicao AS refeicao
            INNER JOIN refeicao_alimento AS opcao
            INNER JOIN alimentos_refeicao AS cardapio
            WHERE cardapio.id_refeicao = refeicao.id
            AND cardapio.id_alimentos = opcao.id
            GROUP BY refeicao.id");

        $saida = '{"refeicao":';
            $saida .= "[";

            while($r = $sql->fetch_array(MYSQLI_ASSOC)){
                if($saida != "["){$saida = ", ";}
                $saida.= '{"nome":"'.$r[0].'",';
                $saida.= '"id_refeicao":"'.$r[1].'"}';
                //$saida.= '"senha":"'.$r["senha"].'"}';

                $id_refeicao = $r[1];

                $sql2 = $db->query ("SELECT refeicao_alimento.nome
                    FROM refeicao_alimento
                    INNER JOIN refeicao_refeicao
                    INNER JOIN alimentos_refeicao
                    WHERE alimentos_refeicao.id_alimentos = refeicao_alimento.id
                    AND alimentos_refeicao.id_refeicao = $id_refeicao
                    GROUP BY refeicao_alimento.id");

                while($sr = $sql->fetch_array(MYSQLI_ASSOC)){
                        if($saida != "["){$saida = ", ";}
                        $saida.= '{"nome":"'.$r["nome"].'"}';

                };

            };
        $saida .= "}"; echo json_encode($saida); ?>

Eu precisaria que ele imprimisse um json dessa api, algo assim para 7 refeições diferentes:
{almoco: [
    {"Opção 1": "Até 5 colheres de sopa de arroz integral ou qualquer outro carboidrato + proteína (Carne, ovos, peixe, frutos do mar, frango, o tanto que quiser até saciar"},
    {"Opção 2": "Proteína (Carne, ovos, peixe, frutos do mar, frango, o tanto que quiser até saciar + couve flor gratinada (ver receita) + arroz integral + salada verde à vontade." },
    {"Opção 3": "Três colheres de sopa de purê de batata doce ou de abóbora (80 gramas) com filé de peixe ou qualquer outra proteína (Carne, ovos, peixe, frutos  do mar, frango, o tanto que quiser até saciar) + até 4 colheres de sopa de legumes cozidos + salada verde à vontade."},
    {"Opção 4": "Um pedaço de 150g de torta funcional de frango (ver receita ) + salada verdade à vontade."},
    {"Opção 5": "Arroz integral + proteína (Carne, ovos, peixe, frutos do mar, frango, o tanto que quiser até saciar) + até 1 concha rasa de feijão + salada verde à vontade. Usar esta opção somente uma vez na semana."},
    {"Opção 6": "Strogonoff fit de carne ou frango (ver receita) + até 5 colheres de arroz integral + salada verde à vontade."},
    {"Opção 7": "Suflê de frango (ver receita) + purê de batata doce ou abóbora + salada à vontade."},
    {"Importante": "É obrigatório o carboidrato no almoço. E aqui são opções de como usar as proteínas e carboidratos, mas podem utilizar de outra forma se quiserem."}

]}
E para o usuário:
Café da Manhã
Lista de Opções:
Uma fatia de pãozinho funcional (ver receita) + ovos mexidos + uma fatia de queijo + chá em sachê ou café com adoçante.
Crepioca (ver receita) com recheio de Requeijão light e orégano + chá em sache ou café com adoçante.
Pão de queijo de frigideira (ver receita) + chá em sachê ou café com adoçante.
Até 5 bolachas de arroz integral + ovos inteiros (tanto que precisar) + uma fatia de queijo + chá em sachê ou café com adoçante.
Pãozinho de batata doce (ver receita) + chá em sachê ou café com adoçante.
Um pedaço de bolo de cenoura (ver receita+ chá em sachê ou café com adoçante.
Um pedaço de bolo de banana (ver receita) + chá em sachê ou café com adoçante.
Mingau de aveia com banana e cacau.
Ovos (tanto que precisar) + uma fruta + 2 colheres de sopa de aveia.
Panqueca de banana ou coco (ver receita) com pasta de amendoim + chá em sache ou café com adoçante.
Almoço
Lista de Opções:
Até 5 colheres de sopa de arroz integral ou qualquer outro carboidrato + proteína (Carne, ovos, peixe, frutos do mar, frango, o tanto que quiser até saciar) + salada verde à vontade.
Proteína (Carne, ovos, peixe, frutos do mar, frango, até 200g) + couve flor gratinada (ver receita) + arroz integral + salada verde à vontade.
3 colheres de sopa de purê de batata doce ou de abóbora (80 gramas), com uma proteína (Carne, ovos, peixe, frutos do mar, frango, até 200g) + até 4 colheres de sopa de legumes cozidos + salada verde à vontade.
1 pedaço de torta funcional de frango (ver receita ) + salada verdade à vontade.
Arroz integral + proteína (Carne, ovos, peixe, frutos do mar, frango, o tanto que quiser até saciar)+ até 1 concha rasa de feijão + salada verde à vontade.
Strogonoff fit de carne ou frango (ver receita) + até 5 colheres de arroz integral + salada verde à vontade.
Suflê de frango (ver receita) + purê de batata doce ou abóbora + salada a vontade.
Comment: Voce cria apelidos para tabelas que nem possuem nomes de campos iguais, deixa de definir uma váriavel para seu vetor percorrer com while, não define os campos que irá percorrer, e criar JOIN com apelidos de tabela chamando campos que não estão no Select, ou seja, irá ficar anos e não ira funcionar, vou postar uma resposta mas não entendi lendo seu código diversas vezes quais os campos quer dar select, se falasse os campos e quais tabelas eles estão referentes seria ótimo. E outra, você percorre um while e define uma váriavel $r e ao invés de colocar nome de tabela coloca números
Answer: query("SELECT * FROM refeicao_refeicao
            INNER JOIN refeicao_alimento ON refeicao_refeicao
            INNER JOIN alimentos_refeicao ON refeicao_refeicao
            WHERE cardapio.id_refeicao = refeicao.id
            AND cardapio.id_alimentos = opcao.id
            GROUP BY refeicao.id");

Tenta assim, se não der tente relacionar o id na tabela que esta dando o select por exemplo:
query("SELECT * FROM refeicao_refeicao
                INNER JOIN refeicao_alimento ON refeicao_refeicao.refeicao_alimento_id=refeicao_alimento.refeicao_alimento_id
                INNER JOIN alimentos_refeicao ON refeicao_refeicao.alimentos_refeicao_id=alimentos_refeicao.alimentos_refeicao_id
                WHERE cardapio.id_refeicao = refeicao.id
                AND cardapio.id_alimentos = opcao.id
                GROUP BY refeicao.id");

Assim ele vai ligar como uma chave estrangeira então sera necessario criar o id das demais tabelas inseridas com o inner join.
Espero ter ajudado, qualquer coisa mande um feed back do resultado :D
Answer: Não entendi muito bem seu JOIN mas vou postar seu código com algumas coisas corrigidas, e se caso não funcionar comente o que esta acontencendo
Primeiro erro: Logo no começo você cria uma query na váriavel que está fazendo select, isto é errado, deveria primeiro fazer o select depois setar a query.
Segundo erro: cometido é definir apelidos para campos / tabelas que não possuem nome idêntico.
Terceiro erro: seu While define mysqli_fetch_array e você seta como parâmetro o MYSQLI_ASSOC, portanto mas um erro encontrado. Conflitando ARRAY com ASSOC
Quarto erro: Seu While está a percorrer tabelas mas você indica para o While que a váriavel $r ira percorrer número invés de tabela indicando $r[0] e $r[1] enquanto deveria informar o nome de uma tabela existente no banco de dados.
$sql = "SELECT * FROM REFEICAO_REFEICAO A
            LEFT OUTER JOIN REFEICAO_ALIMENTO B ON (A.ID = B.ID)
            LEFT OUTER JOIN ALIMENTOS_REFEICAO C ON (B.ID = C.ID_ALIMENTOS) GROUP BY A.id ";

$resultado = $db->query($sql);

$valores = array();

if($resultado){

    while($row = $sql->fetch_assoc(MYSQLI_ASSOC)){

        $valores['nome'] = $row['nome'];
        $valores['id_refeicao'] = $row['id_refeicao'];
        $valores['senha'] = $row['senha'];

        array_push($valores, $novo);
    }

} else {
    return json_encode(array( 'error' => mysqli_error($conn) ));
}
    return json_encode($valores);

Web Service PHP com INNER JOIN


Há como criar um repositório no GitHub com um projeto já desenvolvido?

Question: Meu problema consiste que tenho um projeto no GitHub e esse projeto está sendo  desenvolvido por mim e mais duas pessoas. Porém, de repente, realmente não sei o que aconteceu, o meu projeto que estava todo organizado, deixou de permitir que pudesse fazer o commit, push e pull diretamente do Eclipse. Tentei pô-lo no repositório novamente, tentei cloná-lo, mas o git disse que parte do projeto já estava no computador e só me permitiu a inclusão das classes básicas (que tb. estão no meu repositório antigo). Não sei o que fazer. Para isso, uso o Git para Windows. Porém, meus colegas vem comitando código e mesmo atualizando código não consigo ter os mesmos resultados. Por exemplo, na GUI, quando rodo o programa, obtenho resultados diferentes do que é esperado (que é o que meus colegas obtêm) como desfiguração da tela, aparece de uma forma diferente do que há  no Windows Builder.
Por isso, queria criar um novo repositório, porém que "iniciasse" com código do meu projeto, bastando aos outros cloná-lo e começar a comitar lá, pq tá muito complicado, como proceder?

Quando tento importar o projeto que baixei do outro repositório pelo Eclipse usando o comando import > git > projects from github > existing local  repository > nome_repositorio > vai para a parte da imagem. Não consigo completar a ação (já tinha feito o repositório). Porém aparece essa imagem.

Ele não permite fazer do projeto todo, apenas das classes básica. Quem souber me ajudar quanto a isso e melhor ainda, permanecendo no mesmo repositório, agradeço mesmo.
Comment: quando você tenta realizar o commit, o git apresenta algum erro?
@JNMarcos
Comment: Não entendi o problema @JNMarcos, não é só criar o repositório novo  e fazer um push inicial com todo o projeto?
Comment: @WellingtonSilvaRibeiro sim. Para se fazer isso, segue-se esses passos?
Comment: @WellingtonSilvaRibeiro sim. Para se fazer isso, segue-se esses passos? 1. criar repositório no site GitHub. 2. clonar o repositório para a máquina e depois? Pois o meu projeto não apresenta as opções em team de comitar, push, pull.
Answer: Você pode adicionar um novo origin no seu git. Para isso use o comando git add origin remotenovo url-do-seu-novo-repositorio.
Depois basta fazer um commit e um push para o novo repositório:
git push -u remotenovo master

Pronto.
Comment: Na verdade é add origin
Comment: Ele diz que origin não faz parte do conjunto de palavras de comando. Tem como destrinchar um pouco mais. Não sei usar por meio do Shell.
Comment: Ah cara, eu inverti o comando. Vou ajustar aqui


Safe access to file from two processes

Question: Suppose I have two processes. One always resides in memory and periodically reads some settings from a file on a disk. If it detects that settings was changed then it applies them.
The other process runs under command line by demand and modifies the settings. Thus the first process only read the file and never write to it while the second can only write to the file.
Should I synchronize the access to the file to ensure that the first process will always get consistent settings i.e. before or after modifications not some intermediate contents? If yes, what is the simplest way to do this in C++.
I'm interested mainly in cross-platform ways. But also curious about Windows- and/or Linux-specific ones.
Answer: Use a named semaphore and require either process to hold the semaphore before editing the file on disk. Named semaphores can be  connected to by any running application.
Look at man 7 sem_overview for more information on named semaphores on linux machines.
The closest equivalent for windows I can find is http://msdn.microsoft.com/en-us/library/windows/desktop/ms682438(v=vs.85).aspx
Answer: You are using C++ so your first option should be to check through the usual cross-platform libs - POCO, Boost, ACE, and so forth to see if there is anything that already does what you require.
You really have two separate issues: (1) file synchronization and (2) notification.
On Linux to avoid having your daemon constantly polling to see if a file has changed you can use inotify calls and set up events that will tell you when the file has been changed by the command line program.  It might be simplest to look for IN_CLOSE_WRITE events since a CL prog will presumably be opening, changing, and closing the file.
For synchronization, since you are in control of both programs, you can just use file or record locking e.g. lockf, flock or fcntl.
Answer: The most obvious solution is to open the file in exclusive mode. If the file can not be opened, wait some time and try to open the file again. This will prevent possible access/modification conflicts.
The benefit of this approach is that it's simple and doesn't have significant drawbacks.
Of course you could use some synchronization primitives (Mutex, Semaphore depending on the OS) but this would be an overkill in your scenario, when speedy response is not required (waiting 200 msec between open attempts is fine, and writing of config file won't take more).

Safe access to file from two processes


Estimating accurately the mean of an autocorrelated bounded integer time series

Question: I have a bounded integer time series $X_{1:\infty}$ ($1\leq X_k\leq M$), and I want to estimate the mean
$$ s = \lim_{L\to\infty} \frac{1}{L}\sum_{k=1}^L X_k. $$
I'm assuming it exists and that $X_k$ converges in distribution to some distribution with mean $\mu$ and variance $\sigma^2$, and $s$ converges to $\mu$.
I am estimating it for $X_{1:L}$ as $s_X = L^{-1}\sum X_{1:L}$, and the accuracy of $s_X$ I can estimate using
$$ \mathbb{V}[s_X] = \frac{\sigma^2}{L} + \frac{2}{\sigma^2L} \sum_{\tau\geq1} \mathrm{Acf}(\tau)(1-\tau/L), $$
by replacing $\sigma$ and the autocorrelation function $\mathrm{Acf}(\tau)$ with the sample standard deviation and the sample a.c.f..
The asymptotic distribution of $X_k$ seems to be quite unusual, with 75% of values being $\leq 4$, and approximately power-law-like distributed up to the maximum $M\sim10^4$. The mean and s.d. are about 12 and 150. The autocorrelation function seems to decay roughly exponentially as $\mathrm{Acf}(\tau)\sim 2^{-\tau}$ until trailing off at $\mathrm{Acf}(\tau)\approx 10^{-3}$.
So with these unusual properties of $X_k$, how well can I expect $s_X$ to estimate the limit, and how can I check how good it is?
More importantly, are there some better estimators that I can try?
Comment: You may be able to derive an anylitical solution with the conditional distribution of $X_k $.  I.e. $f (X_k | X_1,...,X_{k-1})$.  Can you tell us what that conditional distribution is?  Other than that you can always simulate the process and estimate the mean many times which will give you an emperical approximation for the estimators variance.  The estimators bias could also be approximating with bootstrapping techniques.  All that said, it is still probably better to work with an analytical solution using the conditions where possible.
Comment: @ZacharyBlumenfeld I am unable to derive the distribution in closed form. Simulating it is what I've been doing so far: my question is what's the best way to extract an accurate estimate from the process sample I have. Is it possible to do better?
Comment: The answer is yes.  You can use Feasible Generalized Least Squares (FGLS) to produce a more efficient estimate.  This is a special enough case though that an answer can be made really simple.  Will try to get to it later.
Comment: You seem to be estimating the variance of the mean without smoothing. This will result in an inconsistent estimator of the variance. In such a case you would need to use "fixed-b" asymptotics. Two questions (I happen to be aware of because I contributed) dealing with the issue are http://stats.stackexchange.com/questions/153444/what-is-the-long-run-variance and http://stats.stackexchange.com/questions/60942/newey-west-t-stats-and-critical-values
Answer: The Problem
To re-state the problem: You have a time series $\{X_t\}_{t=1}^\infty$ and are interested in estimating the unconditional mean, $E[X_t]$.
You do not know the conditional distribution of $X_t$ (i.e. $f(X_t|X_1,...,X_{t-1})$ is unknown).  However, you do know that the time series is stationary and ergodic (obviously) and that it is homoscedastic; $var(X_t)=\sigma^2\;\;\forall t \in \mathbb{N}$.
Also, for any lag $k \in \mathbb{N}$ you know the auto-correlation coefficient $\rho_k = cor(X_t,X_{t-k})$ (at least you can approximate it well in a large enough sample). With this information, you can write the covariance matrix for the finite sample $X_1,...,X_T$;
$$
\mathbf{cov}(X_1,...,X_T)=\Sigma = \sigma^2 R
$$
where
$$
R=\begin{bmatrix}
  1 & \rho_{1} & \cdots & \rho_{T-1} \\
  \rho_{1} & 1 & \cdots & \rho_{T-2} \\
  \vdots  & \vdots  & \ddots & \vdots  \\
  \rho_{T-1} & \rho_{T-2} & \cdots & 1
 \end{bmatrix}
$$
Deriving The Best Linear Unbiased Estimator (BLUE)
(See the Wikipedia entry on GLS and the references cited therein for more details on what follows)
Define the vectors $\mathbf{X} = (X_1,X_2,...,X_T)$ and $\boldsymbol{\mu}=(\mu,...,\mu) \in \mathbb{R}^T$.  You can consistently estimate $E[X_t]$, by minimizing the following quadratic
$$
\hat\mu_{W} = \min_\mu\bigg\{(\mathbf{X}-\boldsymbol{\mu})'W(\mathbf{X}-\boldsymbol{\mu}) \bigg\}
$$
Where $W$ is a $T\times T$ positive-definite symmetric matrix.  The closed form solution is
$$
\hat\mu_{W} = (\mathbf{1}'W\mathbf{1})^{-1}\mathbf{1}'W\mathbf{X}
$$
where $\mathbf{1}$ is a $T\times 1$ vector of ones.  The common sample average $\frac{1}{T}\sum_{t=1}^T X_t$ is a special case of the above where we choose $W \propto I$, where $I$ is the identity matrix*.
*As a side note, $\hat\mu_{W}$ is indifferent to proportionality constants in $W$. i.e. $\forall\; a \in \mathbb{R}_{++}$, $\hat\mu_{W}=\hat\mu_{aW}$.
Any choice of $W$, so long as it is positive-definite and symmetric, will result in a consistent estimator of $E[X_t]$.  In other-words, it can be shown that as $T\rightarrow \infty$; $\hat\mu_{W}\stackrel{p}{\rightarrow} E[X_t]$, $\forall\; W \in \mathcal{S}$,where $\mathcal{S} \subset \mathbb{R}^{T\times T}$ is the subset of all positive definite symmetric matrices.
However, some choices of $W$ yield more efficient (lower variance) estimates than others.  It can be shown that the most efficient choice of $W$, resulting in the Best-Linear Unbiased Estimate (BLUE) of $E[X_t]$, is $W \propto \Sigma^{-1}$.  In your case, you can use;
$$
\boxed{
\hat\mu_{R^{-1}} = (\mathbf{1}'R^{-1}\mathbf{1})^{-1}\mathbf{1}'R^{-1}\mathbf{X}
}
$$
Variance and Other Asymptotic Properties
$\hat\mu_{R^{-1}}$ is unbiased, consistent, efficient, and asymptotically normal:
$$
(\hat\mu_{R^{-1}} - E[X_t])\ \xrightarrow{d}\ \mathcal{N}\!\left(0,\,\sigma^2(\mathbf{1}'R^{-1}\mathbf{1})^{-1}\right)
$$
So
$$
var(\hat\mu_{R^{-1}}) \approx \sigma^2(\mathbf{1}'R^{-1}\mathbf{1})^{-1}
$$
Follow Up and Simulation
Because your data is bounded and integer valued, the asymptotic approximations given above may not work well for reasonably sized finite samples.
Also, even though $\hat\mu_{R^{-1}}$ has a lower variance than
$\hat\mu_{I}=\frac{1}{T}\sum_{t=1}^T X_t$, the difference may be negligibly small.  If that is the case  you may prefer to use $\frac{1}{T}\sum_{t=1}^T X_t$ since calculating $\hat\mu_{R^{-1}}$ is much more computationally expensive.  You can calculate the difference in variance analytically to get an idea.
To analysis how well the normality approximation works you can do the following:

simulate $(X_1,...X_T)$ and collect $\hat\mu_{R^{-1}}$ and $\hat\mu_{I}$ multiple times.  If you are given the data $X_1,...X_T$ and cannot directly simulate it, you can use a block-bootstrap.
Plot the histogram of $\hat\mu_{R^{-1}}$ and $\hat\mu_{I}$.  Do they look approximately normally distributed? Are the sample variance of the estimates close to the asymptotic approximations?

If the asymptotics don't seem to approximate well, you could either increase $T$ or use the empirical results of the simulation in place of the asymptotic results.


How to prove that $X, Y,$ and $Z$ are collinear if and only if $\cos A \cos B \cos C =\frac{-3}{8}$?

Question: Let $X, Y, Z$ be the reflections of $A, B$, and $C$ across the lines $BC, CA,$ and $AB$, respectively. How to prove that $X, Y,$ and $Z$ are collinear if and only if $\cos A \cos B \cos C =\frac{-3}{8}$? for example α=120, β=γ=30.
Comment: I don't know if it may help, but your condition can be rewritten as $$\cos2A+\cos2B+\cos2C={1\over2}.$$
Answer: In order to obtain manageable formulas we have to destroy the inherent  symmetries of the problem.
Represent $A$, $B$, $C$ as complex numbers with $A$ at the origin and $B\vee C$ horizontal as in your figure. Then, up to similarity, we have
$$A=0,\quad B=-\sin\gamma\> e^{-i\beta},\quad C=\sin\beta\> e^{i\gamma}$$
and
$$X=2i\>\sin\beta\>\sin\gamma,\quad Y=-\sin\gamma\>e^{i(\beta+2\gamma)},\quad Z=\sin\beta\>e^{-i(2\beta+\gamma)}\ .$$
The three points $X$, $Y$, $Z$ are collinear iff
$${X-Y\over Z-X}\in{\mathbb R},\qquad{\rm resp.},\qquad(X-Y)(\bar Z-\bar X)\in{\mathbb R}\ .$$
This amounts to
$$\sin\gamma\bigl(2i\sin\beta+e^{i(\beta+2\gamma)}\bigr) \sin\beta \bigl(e^{i(2\beta+\gamma)}+2i\sin\gamma\bigr)\in{\mathbb R}\ .\tag{1}$$
Here the factor $\sin\beta\sin\gamma>0$ can be omitted, so that $(1)$ can be rewritten in real terms as
$$\cos(\beta+2\gamma)\bigl(\sin(2\beta+\gamma)+2\sin\gamma\bigr)+\bigl(2\sin\beta+\sin(\beta+2\gamma)\bigr)\cos(2\beta+\gamma)=0\ .\tag{2}$$
Now Mathematica found out for me that the left hand side of $(2)$ can be factored into
$$\sin(\beta+\gamma)\bigl(2\cos(2\beta+2\gamma)+2\cos(2\beta)+2\cos(2\gamma)-1\bigr)\ .$$
Since $\sin(\beta+\gamma)\ne0$ we may conclude that $$\cos(2\alpha)+\cos(2\beta)+\cos(2\gamma)={1\over2}\ ,$$
which according to @Aretino 's   comment  is equivalent to your claim.


What type of statistics test do I use for the following

Question: I have three sets of means. For instance
mean.a = [3,2,7,3,8,2,5,7,3,2,5]
mean.b = [9,7,9,10,7,13,30,17,16,9,9]
mean.c = [23,24,25,23,22,22,21,9,25,34,12]

And for each mean, I have standard deviations.
sd.a = [.1,.18,.12,.24,.12,.16,.25,.1,.1,.23,.11]
sd.b = [.3,.13,.1,.24,.2,.1,.24,.11,.1,.23,.1]
sd.c = [.3,.1,.33,.21,.32,.35,.31,.3,.33,.42,.42]

I want to statistically show that a is less than b and c. How can I do this, and find a p value for this? Note that the values are paired. So, for instance, the 5th value of a should be less than the 5th value of b and 5th value of c.
It was suggested to me to use a Wilcoxon signed rank test to show, firstly, that c > b then that b > a. I found the R function wilcox.test(a, b, paired=T). However, I have means and SDs for both a and b, so how would I do this?
Comment: Although it makes little difference here, because the differences between the sets are blatantly obvious, it is strange to have means reported to less precision than indicated by the standard deviations. This renders the SDs almost irrelevant.
Comment: @Peter because the SD of the (rounded or truncated) data will be orders of magnitude greater than the reported SD of the data themselves. That implies replacing the reported SDs by zero will create only inconsequential changes.
Comment: Does the order of these points have meaning? Really I am asking if the data are naturally paired. If so the paired t test or more generally the Wilcoxon signed rank test can be applied to looking at differences of b with a or c with b.
Comment: The order does have meaning yes. So ideally, b and c would be less at all positions than a.
Comment: @codeguy: I think what Michael was asking is whether there is pairing. Is the (say) fifth value of group A matched to the fifth value of group B and C? Your answer seemed to be about the logical order of the three treatment groups, not about pairing or matching of the values in the groups.
Comment: Yes, they are paired by your definition.
Comment: @whuber Although I agree it is strange to see the means reported to less precision than SDs, I don't see why it makes the SDs almost irrelevant. Can you explain?
Answer: Given that the order is meaningful then a paired test such as the Wilcoxon signed rank test could be applied.  It does not compare means.  It is the original pair measurements that are differenced. Because of random variation it is not necessary for all paired differences for b-a to be positive for the test to be meaningful.
Since you want to show c>b and b>a you want to do two tests and should make a p-value adjustment for multiple testing.
Comment: A minor point - I think he wants to show $c>a$ and $b>a$, not the full ordering, but your point still applies.
Comment: @jbowman Thanks.  All I was suggesting was the two comparisons so the full ordering would require a third test and so I made the change you suggest.
Comment: how do I do this given that I have means and standard deviations?
Comment: I found the R function `wilcox.test(array1, array2, paired=TRUE)`, but I have means and SDs for each of `array1` and `array2`.
Comment: @CodeGuy You can't.  You need the raw data.  If you want to do component-wise tests and are willing to assume normality (not sure it is a good assumption) you can do unpaired t tests.  That would give 11 tests for each of the comparisons (c with b and b with a).  That would be a total of 22 hypothesis tests.  The multiplicity correction becomes very important now.  Of course given the magnitude of the difference in means relative to their standard deviations the p-values should be very small.
Comment: Is your alternative hypothesis that all the components of b are larger than all the corresponding components of a and similarly for c with b?
Comment: So really, I need to run the wilcox test using matrices
Comment: Yes, that is the alternative hypothesis.
Comment: @CodeGuy You could do all the t tests and apply Bonferroni or some other adjustment.
Comment: I do have the raw data, so I can just do Wilcoxon right? It says that Wilcoxon shows that two data sets are non-identical. But does this say that "a" is less than "b" if p < 0.05 for a Wilcoxon test with "a" and "b"
Comment: It tests for location shifts. You can do a one-sided or a two-sided test.  If the test leads to a statistically significant result you can conclude that they differ in location in the observed direction.


Client-Side Equivalent of drupal_set_message with javascript

Question: I've got javascript that notifies the user of actions and errors, and I'd like to use the existing Drupal messaging. Is this built in to Drupal?
Alternatively, (I'm fairly new to Drupal and am not very familiar with the modules available) if this is available as a module, I haven't been able to find it. Does anyone know of a module?
UPDATE: To clarify, I'm trying to set a Drupal message from the client-side (JavaScript), on a page that has already rendered. This is a very AJAXy page with tonnes of functionality that sometimes requires messages be shown to the user.
Is there is a provision in the Drupal client-side API for setting messages?
Comment: hello. I do not know if others, but to me your question is not all clear (sorry). do you want show messages from a module of Drupal using javascript?
Comment: Can you post some of your javascript code?
Comment: @Martin Schlagnitweit This is legacy js that I'm porting into Drupal... the legacy code is kind of irrelevant -- it just manually created it's own message in the old system.
Comment: If there is nothing in the client-side API for this, I guess this is a good candidate for a new module?!
Comment: @moon.watcher I want to show messages from JavaScript. Incidentally, this js is part of a module, but I don't think that's relevant in this case.
Answer: I don't see JS API for dispaying messages even in D7. Maybe because all you need is DIV with classes like messages,status warning or error. You can see how drupal works with it in file /misc/tabledrag.js.
When you drag rows in tables drupal shows you a warning message with this code:
$(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');

Comment: Okay, that's it then... I smell a new module coming on to reduce duplicate code...
Thanks @kalabro


Is it reasonable to represent mean value without removal of the outliers?

Question: At first, I want to say, I know that mean is outlier sensitive.
Problem
I have to talk about the lifestyle of the students, where the data is quantitative. Let's say I have to talk, how much time a student spend in the classroom (A), how much time a student spend in library (B) etc. Some of the data set (e.g. A) contains outlier. Since I believe that extreme users are representative of the population who does/uses extremely, I do not want to remove outliers and I want to write about the lifestyle of the students using the mean value without removal of outliers.
What creates the problem?
This paper says mean is outlier sensitive and many other articles says, you should remove outliers when calculating mean. However, I have never read a research paper where researchers have talked using median value, at time of talking lifestyle. For instance: I have never read a paper where researchers said "students spend 1 hour in the library" where 1 hour was median value.
My Question
I will show median values for each type of data (e.g. spending time in library, spending time in classroom) along with mean value in the table. Without removal of outliers, will it reasonable if I talk about the lifestyle of the students in everywhere except the table using only mean value?
Thanks in advance!
Answer: First off, kudos on recognising that outliers should be retained!
You seem to be most interested in how to characterize the population (students). Means and medians are both commonly used to convey what a 'typical value' of the population (loosely speaking) is. If the distribution is highly skewed and the mean does not capture a 'typical value' well, you may not want to use it (though there are exceptions to this). In this case, it's quite reasonable to use the median instead. Alternatively, you can use the mean along with confidence intervals (which can be asymmetric and convey a skewed distribution). Another common strategy that may be less useful to you in this specific case is to transform (e.g. take the log) the data so that it becomes less skewed; this is frequently a good way to plot data that is highly skewed.
Bottom line: it depends on what you want to communicate. In your case, I would use the median, but be sure to make this clear so your audience understands what is being discussed.
Comment: @SabbirAhmed You can use medians for all categories to make it simple. To oversimplify a bit, the more symmetric a distribution is, the more similar the mean and median are. For a perfectly symmetric distribution, the mean and median are identical. So there's no downside to using the median for less skewed distributions too.
Comment: we have dataset where each category contains a specific type of data. So, if we start talking about mean, for the category which is highly skewed can not be described using median value, I think. I think, we have to describe the lifestyle using a specific method mean/median.
Answer: Removal of outliers for computing the mean is certainly not mandatory, and may actually in some cases not make much of a difference (if the outliers are not that far out, and their percentage is small). Surely removal of outliers is more sensible if there are reasons to believe that these observations are erroneous, but you seem to be sure that yours are not, which is a good reason not to remove them.
If in fact the mean is strongly influenced by the outliers, I think it's better to comment using more than one number to get the whole picture. Using mean and median is one option, but maybe in your case it is even more sensible to say something like "the mean is 3 hours, in fact the vast majority is below 3.5 hours, but some 5% spend more than 7 hours per day XXX".
Comment: Great answer, thanks for your information "the mean is 3 hours, in fact the vast majority is below 3.5 hours, but some 5% spend more than 7 hours per day XXX".
Comment: Can you please cite a paper or reliable article where you got "Surely removal of outliers is more sensible if there are reasons to believe that these observations are erroneous". I guess, this is a belief. However, providing paper would help me more to go on.
Comment: I will accept your answer if you please can provide a research paper or reliable article regarding this.
Comment: I'd expect that this can be found somewhere, but my answer is not taken from some published paper but rather a result of experience and thought, (critical) reading of lots of literature about robust statistics and outliers, and regular attendance of conferences where these things are discussed. Unfortunately I'm not that familiar with the literature that explains these things properly to beginners. In order to find something published that says what I've just written I'd need to google and you can do that yourself.
Comment: Some of this is just simply logical, like that outliers should be removed if they are erroneous (although in many cases one can't know for sure) and that if they are not erroneous you'd remove valid information, which can do harm. About the influence of outliers you can find out yourself, comparing your mean before and after outlier removal. Sorry I'm more of a self-made statistician than a literature recommender.


How to use getPage() on a request with a request body?

Question: At work, I am using HtmlUnit version 2.8, and I've come to this kafkaian situation:
I have a WebRequest that has a body, thus no request parameters: using WebRequest.setRequestParameters() when the request body is not null throws a:
java.lang.RuntimeException: Trying to set the request parameters, but the request body has already been specified;the two are mutually exclusive!

(source available here)
However, when I use webClient.getPage(webRequest), I get:
java.lang.NullPointerException: parameters

(source here)
That really verbose message meaning that it's not OK to have null for request parameters.
Is there a way to fix this, or bypass it? Preferably using same version (again, 2.8), as I don't have the rights to do upgrade the frameworks we use.
Comment: that moment when you have to choose between a NullPointerException or a RuntimException... Such dilemma
Answer: Well the default constructor initializes by default the request's parameters to Collections.emptyList(), so it will not cause the NullPointerException.
What did cause my exception though, was that a few lines before I called
request.setRequestParameters(null);

which obviously was the cause to my issue.
I removed that line and now it works just as expected.


Why is the UIPageViewController resizing its UIViewControllers views after the page turn?

Question: Within the pageViewController:viewControllerAfterViewController: method, just before the return statement, the view which is about to be returned as the next page has the correct view frame size.
However immediately after the pageViewController:didFinishAnimating:previousViewControllers:transitionCompleted: method is called, I check the frame size of the newly introduced view controller ([pageViewController2.viewControllers objectAtIndex:0];) and I find it resized.
Note that, I have set [self.pageViewController.view setAutoresizesSubviews:NO] and the autoresizing mask to None for the newly created ViewController.
Any ideas in which step the new ViewController is being resized?
Answer: I think the problem is inherently related to the nature of UIPageViewController. It is built from UIScrollView. I don't exactly know why there is strange resizing behavior, but it seems to be particularly pronounced when the view controllers that make up your pages use auto layout. Seemingly, locking the constraints in your page view controllers to the superview makes the elements resize after the transition because the superview is itself getting resized after said transition.
This sucks because Apple is basically pushing all of us to adopt auto layout. Auto layout is awesome, and I recommend everyone use it from now on, but it really really sucks when you use it with a UIPageViewController. They really ought to either scrap that class or build something easier for developers, something that can be dragged into a storyboard outright.
A few things to consider.
1.) Don't lock anything to the "Top Layout Guide" or the "Bottom Layout Guide". Also make sure you have "Constrain To Margins" disabled on any view intended to hug the sides of the screen.
2.) If you are using a label in your individual page / content view controllers, make sure you bind/constrain it to something other than the superview. I wanted to place a label over a UIImageView, so I aligned the label to the leading and top edges of the image view (using AutoLayout constraints only), creating an offset to give the label some margins.
3.) The following would otherwise be a good tutorial. However, it is a bit outdated. I downloaded the project and basically modified it to get a UIPageViewController implementation that works. The only problem with this project is that it doesn't use AutoLayout. I'm currently writing a blog post that more clearly discusses how to use UIPageViewController and Autolayout together.
http://www.appcoda.com/uipageviewcontroller-storyboard-tutorial/


Como obter o número do CPF/CNPJ de um certificado digital do tipo e-CPF/e-CNPJ nos modelos A1 e A3?

Question: Eu estou desenvolvendo um método alternativo para login via certificado, sem precisar de java ou uma linguagem expecífica, apenas http e php para processar informações backend(mas que poderia ser manipulado por qualquer outra linguagem que processe http). Os métodos mais comuns que existem são o da Certsign, porém elepossui uma baixa interoperabilidade limitando-se à linguagens como .NET e Java. Além disso este método depende do web-service deles para se obter os CPF do certificado, caso o sistema deles esteja fora não é possível altenticar o usuário.
Sabemos que é possível solicitar o certificado através do SSL Handshake, que habilita o servidor web à abrir uma solicitar o certificado do cliente dentro de uma cadeia de certificados pré-selecionada, o que fará exatamente o que a Certsign faz.
Os dados que eu consigo extrair de um certificado NF-e são esses(obfuscado):

Já fizemos a solicitação de um e-CPF e um e-CNOJ, a questão está, aonde dentro dos dados publicos do certificado estão as informações referente ao número do cpf ou cnpj?
Comment: _ Por favor, quem está negativando esta pergunta favor comentar o motivo e o que fazer para ser merecedor do teu digníssimo apoio. _
Answer: Após obter um certificado A1 e A3 válido (e não os de testes que foram usados para confecção da pergunta), foi possível identificar que no  campo S_DN_CN do certificado contém o nome e o número do documento.
No grupo de  Distinguished Name (DN)  no Common Name(CN) do certificado é possível visualizar uma String composta pelo Nome (e-CPF) ou Razão Social(e-CNPJ) seguido de  dois pontos ":"  e a sequência numérica do CPF ou do CNPJ cadastrado.
Por exemplo:
No php é possível obter através da chave SSL_CLIENT_S_DN_CN, exemplo:
<?php

    list ($nome, $documento) = explode(":", $ssl["SSL_CLIENT_S_DN_CN"]);
?>

Após isso pode-se aplicar algorítimos de teste cpf e cnpj para identificar qual tipo de documento representa este certificado.
A descrição da composição do DN pode ser encontrado no item
2.1.12. Composição do Distinguished Name (DN) do certificado e-CPF  e 3.1.12. Composição do Distinguished Name (DN) do certificado e-CNPJ
da documentação https://www.receita.fazenda.gov.br/acsrf/LeiautedeCertificadosdaSRF.pdf
Comment: Por acaso está no item 2.1.12 da documentaçãoi que vc mesmo indicou (3.1.12 para CNPJ). E no 2.2.5 estão outros campos de documentos, cada um com seu respectivo OID.
Comment: Ainda, no mesmo manual, o terceiro campo "OU" indica se é e-CPF ou e-CNPJ, e o respectivo tipo
Comment: Obrigado, acabou passando despercebido!
Comment: Complementando, esta resposta é válida para eCPF e eCNPJ (e vários outros tipos de certificado), mas não serve para todos os certificados ICP-Brasil (sei que a pergunta é só sobre eCPF/eCNPJ, é só para complementar mesmo). Existem, por exemplo, certificados OAB e AC-JUS que possuem o número de registro no DN (ou não possuem número algum), além de outros tipos que podem ter outros dados. Nestes casos, o mais garantido é buscar o CPF/CNPJ na extensão Subject Alternative Name (seção 2.2.5 do documento que vc indicou). E para saber se é A1 ou A3: https://pt.stackoverflow.com/q/418059/112052
Answer: utilizei as seguintes libs e resolvi com o codigo abaixo (to considerando que o p7b tá base64-encoded, mas se o seu p7b não tiver, podem tirar a linha do decode):

       File f = new File("c:/temp/teste.p7b");

       byte[] buffer = new byte[(int) f.length()];
       DataInputStream in = new DataInputStream(new FileInputStream(f));
       in.readFully(buffer);
       in.close();

       byte[] arquivo = org.bouncycastle.util.encoders.Base64.decode(buffer);

       CMSSignedData signature = new CMSSignedData(arquivo);
       Store cs = signature.getCertificates();
       SignerInformationStore signers = signature.getSignerInfos();
       Collection c = signers.getSigners();
       Iterator it = c.iterator();

       byte[] data = null;

       Collection certCollection = cs.getMatches(null);
       Iterator certIt = certCollection.iterator();

        while(certIt.hasNext()) {

            X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

            CMSProcessable sc = signature.getSignedContent();
            data = (byte[]) sc.getContent();

            X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(cert);

            if (certificate.getExtensionValue("220.127.116.11") != null) {
                System.out.println(new String(certificate.getExtensionValue("18.104.22.168"), "UTF-8"));
                System.out.println(certificate);
            }
        }

Comment: Olá Anderson seja bem-vindo ao SOpt !
Bacana seu interesse em ajudar e tenho certeza que sua resposta até possa ajudar outras pessoas, mas a pergunta vai muito além do titulo o conteúdo descrito por quem perguntou contém informações úteis que lhe guiarão a dar uma resposta mais coesa. No caso, a pergunta se referia a um método que não usasse java :)
Comment: entendi, foi a pressa em ajudar. se vc n conseguir, podera expor o java como um webservice e consumi-lo no seu php. abs.
Comment: Da uma olhadinha nessa solução: https://pt.stackoverflow.com/a/195838/7130


If clause in Jess

Question: Could some one please help me using a if clause in jess, I know the simple sintax but I'm trying to use an && operand so I can use two conditions, but nothing I try seems to work.
if((<(?x ?y) && (>=(?z ?s)) then
  ....
else
....

Answer: Jess has a very regular syntax which is quite unlike the Java syntax you're trying to emulate. All "operators" are actually functions, and use the same prefix syntax as function calls.  It's always (op arg1 arg2 ...). The parentheses always surround the whole expression, not just the arguments.
So for example, the Java expression a < b is always (< ?a ?b) in Jess. There is no && operator, but rather, there is an and function. So the Java if (a  d) ... looks like (if (and (< ?a ?b) (> ?c ?s)) then ... in Jess.

If clause in Jess


Is it possible to poll GetKeyboardState() as a replacement for a global keyboard hook?

Question: Is it possible to poll GetKeyboardState() as a replacement for a global keyboard hook?
Answer: I suppose it depends on what you want to do, but probably not.
GetKeyboardState only gets the current state while with the hook you'll get all the keypresses as they come.
I'm not sure if you could even poll it fast enough to be sure to never miss any keypress, but even if you did, if for example the A key was pressed during one poll, and the A key still has the state of pressed during the next poll, how could you tell if that was one long or two fast keypresses.


Do the Pythagorean means preserve the order among groups of observations?

Question: I know that
harmonic mean HM <= geometric mean GM <= arithmetic mean AM
Thus, if I have two groups of observations such that
AM of group 2 > AM of group 1
The smallest possible value of an observation is 1.
Is is true that the same inequality holds for the other two types of means:
GM of group 2 > GM of group 1
HM of group 2 > HM of group 1
Many thanks,
Simone
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: Absolutely no. You will still have $HM\leqslant GM\leqslant AM$ within each group, but that's about it.
Say, our groups are $\{20,20\}$ and $\{5,45\}$. Then $\stackrel{\color{red}{20}}{AM_1}\;<\;\stackrel{\color{red}{25}}{AM_2}$, but $\stackrel{\color{red}{20}}{GM_1}\;>\;\stackrel{\color{red}{15}}{GM_2}$ and $\stackrel{\color{red}{20}}{HM_1}\;>\;\stackrel{\color{red}{9}}{HM_2}$.


Decompose in simple elements

Question: $$F(x)= \frac{(x^2+2x+5)}{(x^2-3x+2)}$$
$$F(x)= \frac{(x^2+2x+5)}{(x-2)(x-1)}$$
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Answer: $$\frac{x^{2}+2x+5}{\left(x-1\right)\left(x-2\right)}=\frac{x^{2}-3x+2+5x+3}{\left(x-1\right)\left(x-2\right)}=1+\frac{5x+3}{\left(x-1\right)\left(x-2\right)}$$
Assume $\frac{5x+3}{\left(x-1\right)\left(x-2\right)}$ is in the form:
$$\frac{A}{x-2}+\frac{B}{x-1}$$
Then $$x\left(A+B\right)-\left(A+2B\right)=5x+3$$
So $-\left(A+2B\right)=3$ and $A+B=5$
Solving for $x$ gives:
$A=13$ and $B=-8$
Answer: This is known as "partial fraction decomposition".  The first step is to make sure the numerator is a lower degree than the denominator.  That is not the case here.  Therefore, to begin, you need to do polynomial long division.  After that division, the numerator will be in the form where the numerator is a lower degree than the denominator.
Then, you have already factored the denominator, so you assume that you can decompose the result into the form:
$$\frac{A}{x - 2} + \frac{B}{x - 1}.$$
Then you cross-multiply these to get:
$$\frac{Ax - A + Bx - 2B}{(x - 2)(x - 1)}$$
Then you set that equal to the numerator, and can solve for $A$ and $B$.

Decompose in simple elements


Views 3, link picture/title to users blog

Question: I have a view of active blog users and I want to link the title of each blogger to their blog ie /blog/[uid].
By default, it seems views can link the blogger title to their profile ie (/user/uid) but I want to link the blogger title to their blog (/blog/uid)
Any idea of how I can go about this please?
Thanks,
Answer: Figured this out:

Add field uid to views.
Go to picture field in views, click rewrite results and output this as link, and then for link path: /blogs/[uid]

Make sure the field uid is visabally above al lthe other field in the view.