Return values for arccosine?

Question: I implemented a day/night shader built on the basis that only pixels on the side of an object that is facing the directional light source are illuminated. I calculate this based on the unit vectors between the directional light's position and the position of the pixel in 3D space:
float3 direction = normalize(Light.Position - Object.Position);
float theta = abs(acos(dot(normalize(Object.Position), direction))) * 180 / 3.14f;
if (theta < 180)
    color = float3(1.0f);
else
    color = float3(0.2f);

return float4(color, 1.0f);

This works well, but since I am brushing up on my math lately, it got me thinking that I should make sure I understand what acos is returning.

Mathematically, I know that the arccosine should give me an angle in radians from a value between -1 and 1, while cosine should give me a value between -1 and 1 from an angle in radians.
The documentation states that the input value should be between -1 and 1 for acos which follows that idea, but it doesn't tell me if the return value is 0 - π, -π - π, 0 - 2π, or a similar range.

Return Value
The arccosine of the x parameter.
Type Description
Name [Template Type] 'Component Type' Size
  x [scalar, vector, or matrix] 'float' any
  ret [same as input x] 'float' same dimension(s) as input x

HLSL doesn't really give me a way to test this very easily, so I'm wondering if anyone has any documentation on this.

What is the return range for the HLSL function acos?
Comment: Return value for `acos()` should be in [0,pi], but I cannot point you (at this time) to an authoritative source for HLSL that says so.
Comment: @njuffa Thanks! I was pretty sure that is what was occurring, and I still need a way to test it which could just be passing in values from `System.Math` into a `cbuffer` and see if the values for `0, 1, -1` are the same for the HLSL `acos`.
Answer: I went through some testing on this topic and have discovered that the HLSL version of acos returns a value between 0 and π. I proved this to be true with the following:
n = 0..3
d = [0, 90, 180, 181]
r = π / 180 * d[n]
c = cos(r)
a = acos(c)

The following is the result of the evaluations for d[n]:

d[0] returns a = 0.
d[1] returns a = π/2.
d[2] returns a = π.
d[3] returns a ~= 3.12....

This tells us that the return value for acos stays true to the range of usual principle values for arccosine:

0 ≤ acos(x) ≤ π

Also remaining consistent with the definition:

acos(cos(θ)) = θ

I have provided feedback to Microsoft with regards to the lack of detailed documentation on HLSL intrinsic functions in comparison to more common languages.

Return values for arccosine?


How do I get feature_importances_ from GridsearchCV

Question: I am fairly new to programming and this problem might be pretty easy to fix, but I have been stuck on it for a while now and I think my approach is just plainly wrong.
As the title indicates, I have been trying to implement a gridsearch on my RandomForest prediction to find the best possible parameters for my model and then see the most important features of the model with the best parameters.
The packages I've used:
import nltk
from nltk.corpus import stopwords
import pandas as pd
import string
import re
import pickle
import os
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics import precision_recall_fscore_support as score
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV

After some datacleaning and preprocessing, I made a gridsearch like this, where x_features is the DataFrame with the tfidfvectorized features of my data:
param = {'n_estimators':[10, 50, 150], 'max_depth':[10, 30, 50, None], 'min_impurity_decrease':[0, 0.01, 0.05, 0.1], 'class_weight':["balanced", None]}
gs = GridSearchCV(rf, param, cv=5, n_jobs=-1)
gs_fit = gs.fit(x_features, mydata['label'])
optimal_param = pd.DataFrame(gs_fit.cv_results_).sort_values('mean_test_score', ascending = False)[0:5]
optimal_param1 = gs_fit.best_params_

My idea here was, that maybe I could make it easy for myself and copy in the optimal_param1 into my RandomForestClassifier(), and fit it on my training data more or less like this:
rf = RandomForestClassifier(optimal_param2)
rf_model= rf.fit(x_train, y_train)

but optimal_param2 is a dict. Therefore I thought transforming it to a string and getting rid of the signs that are too much ( sub : for =, delete {, delete } ) would make it work. That obviously failed as the numbers for n_estimators, max_depth etc. were still strings and it expected integers. What i wanted to achieve in the end was to get an output of the most important features more or less like this:
top25_features = sorted(zip(rf_model.feature_importances_, x_train.columns),reverse=True)[0:25]

I realize that gs is already a complete RF model, but it does not have the attribute feature_importances_ which i was looking for.
I would be very thankful for any ideas on how to make it work.
Answer: Once you have run gs_fit=gs.fit(X,y), you have everything you need and you don't need to do any retraining.
First, you can access what was the best model by doing:
best_estimator = gs_fit.best_estimator_

This is returning the Random Forest that yielded the best results. Then you can access this model's feature importances by doing
best_features = best_estimator.feature_importances_

Obviously, you can chain these and directly do:
best_features = gs_fit.best_estimator_.feature_importances_


Value of polylogarithms $\mathrm{Li}_s(1)$ for $s<1$.

Question: For real $s>1$ the polylogarithm for $z=1$ reduces to the Riemann zeta function $\mathrm{Li}_s(1) = \zeta(s)$. For real $s<1$ Wolfram Alpha and the Wolfram function site give $\mathrm{Li}_s(1) = \infty, s<1$ whereas the mpmath package returns $\mathrm{Li}_s(1) = \zeta(s)$ for all $s\ne 1$. Is this just a convention or is it a kind of continuation for $s?$
Answer: If you define the polylogarithm and zeta functions with the series :$$\operatorname{Li}_s(z):=\sum_{k=1}^\infty \frac {z^k}{k^s}\\\zeta(s):=\sum_{k=1}^\infty \frac 1{k^s}$$
then you'll be in the first case and have to suppose $\;\Re(s)>1\;$ for convergence but if you consider the analytic continuation of these two series as being the actual functions then things become much more interesting and considering every complex $s$ such that $\;s\ne 1\;$ should be the fine choice (see the discussions in the Wikipedia links or here concerning zeta).
Comment: Would $\mathrm{Li}_s(1) = \zeta(s)$ for $s \ne 1$ be  **the** analytic continuation, because this relation holds for $\Re s >1$?
Comment: Yes @gammatester. From the equality for $\Re s >1$ and since $\zeta$ admits a unique analytic continuation over the whole complex plane except $s=1$ we must have the equality for $s\neq 1$ (else $\operatorname{Li}_s(1)$ would not be analytic in $s$ !).


How to merge Ableton audio with Skype audio conversation?

Question: 2011 iMac running Mavericks and Skype 7.36 (507)
I want to be able to talk with someone and share my Ableton audio at the same time.  I know this is a common request as I see it all over the net, and the answers always seem to be either:

Use a commercial application like Audio Hijack or similar
Use SoundFlower or Jack
Use an Aggregate device
Some combination of 1-3

But I believe I have tried every conceivable combination of things that do not require paying for a commercial utility (which I'm not convinced would magically be the solution on its own anyway), and I am still absolutely nowhere.  I even previously asked this question elsewhere and answered it myself, but that answer no longer works for me at all with Ableton (it was Reason-centric at that time).
Even excluding my mic for now, just to pipe the Ableton audio into Skype, what I believe should work but does not, is:

Live's audio device is set to SoundFlower (2 ch.)
Skype's "microphone" preference is set to SoundFlower (2 ch.)
SoundFlowerBed (no longer supported but I'm running Mavericks so it works fine) is set to output to the built-in output (to keep things simple, though my final application will output to my audio interface)

I believe this should send audio out of Ableton and into Skype.  But I get absolutely nothing through Skype.  I'm testing by calling myself on a second Skype account on another computer.  No audio is passed at all from Ableton.
Does anyone know if there is something wrong with what I'm doing above?  Is there another definitive will-always-work way to do this?
MAJOR EDIT:
I just got it working-ish and it was far easier than I had been making it.  However there is a significant issue remaining, which I will cover momentarily.  First, here's what I did, using the SoundSiphon app which while it is a paid app, it allows you to work with the master system output for free, indefinitely... so this is in fact a totally free almost-solution:

Create an Aggregate device consisting of my USB microphone, and the SoundSiphon In device.
In Skype's Microphone selector in Preferences, select the Aggregate Device
Turn on SoundSiphon, set its output to my Audio Interface
In Ableton Live, select SoundSiphon In as the audio device
Make a Skype call and notice the significant remaining issue, to be discussed now.

Audio is now routed from either my mic, or Ableton, but never both at the same time.  Which one I get, depends on which was the last item selected in the Aggregate device.  If I tick the box for SoundSiphon, and then my mic, then I get my mic.  If I tick the box for my mic, and then SoundSiphon, then I get Ableton.
This feels like a bug, but I can't be certain.  To reiterate, either my mic, OR Ableton's audio, will route through to Skype just fine using SoundSiphon.  However the aggregate device does not work as expected, and combine the signals so that I can have Ableton and my Mic sending over Skype together.
This does however present an acceptable workaround, which is to create a separate audio track in Ableton, set my mic as the input there, and simply have Skype listen to Ableton alone, passing my voice to it that way.
I would still love to know why the aggregate device behaves the way that it does, but if nobody can provide an answer to that effect within a few days, I'll create an answer of my own with the all-Ableton audio workaround.
Comment: Why wait to post your own answer? It won't prevent others from answering.
Comment: Oh yeah good point... I always tend to think that once an answer is posted, the question is somehow closed.  But I know that's not the case.  Answer coming right up.
Answer: I have found an acceptable workaround that gets me the end result I needed.  Here's what I did, using the SoundSiphon app which while a paid app, it allows you to work with the master system output for free, indefinitely... so this is in fact a totally free solution:

Get and install SoundSiphon, which is a paid app but the demo version will work for this solution indefinitely
Set SoundSiphon as the audio device for Ableton
Set SoundSiphon as the "microphone" input in Skype Preferences.
Create an audio track in Ableton and set the mic as the input for it.

Now I can talk and my voice comes into Ableton, and all Ableton output goes to Skype.  I can play the sequencer and talk over it, etc.  Works perfectly and this solution is totally free.  Sound quality is of course far from perfect (mono, highly compressed...), but for basic sharing of audio that doesn't have to be pristine, it will definitely do.
I still don't know why the aggregate device approach refused to work, but unless someone else comes up with an explanation there, this is how I'm going to be approaching it going forward.


Iteratively Reference Controls by Name Pattern (VB.NET)

Question: Is there a way to iteratively reference an ASP.NET control based on it's name pattern? Perhaps by a "pointer" or something?
What I have are a large set of comboboxes (each with an associated DropDownList and TextBox control). The DropDownList always has an item selected by default, but the use may wish to submit a NULL value. I come up with the following code to handle three cases: NULL, Existing Item, New Item.
<code>'TextBoxControl & DropDownListControl should iteratively reference their
'  respective TextBox & DropDownList controls by the actual control name
If StrComp(TextBoxControl.Text, DropDownListControl.SelectedItem.ToString) = 0 Then
    'When an Existing Item is selected, Do Something
ElseIf Not TextBoxControl.Text = "" Then
    'When a New Item is entered, Validate & Do Something
Else
    'When NULL, Do Something
End If
</code>
The problem is, with so many comboboxes, I could easily end up with hundreds of lines of code. I wish to handle this in a more dynamic way, but I do not know if it is possible to reference controls in this way. Say I wanted to reference all the TextBox Controls and DropDownList Controls, respectively.
I can do string formatting with a given naming pattern to generate a name ID for any of the controls because they are all named with the same pattern. For example by attaching a specific suffix, say "_tb" for TextBox Controls and "_ddl" for DropDownList Controls:
<code>Left(item.SelectedItem.ToString, item.SelectedItem.ToString.Length - 3) + "_tb"
</code>
Can this sort of thing be done in VB? Ultimately, my goal is to take the value entered/selected by the user, if any, and send it to a stored procedure on SQL Server for insertion into the database.
Answer: Yes. Write your code inside of a function having parameters for the textbox and the dropdown, and then write the function in terms of those two parameters. Then you simply call that function for every set instead of copy/pasting code everywhere.
Don't attempt choosing things by name. That's fragile and imposes machine requirements on a field that'd designed for human consumption.
Comment: Aye, I get that for the most part, but what I'm struggling with is how to convert the name patterned string to the ClientID that references the control object itself. In other words, how do I pass in the string, but reference it as if it were a control ID? Assuming you mean with a "For Each" which is the angle I was approaching it at.
Comment: @Chiramisu: Don't reference the control by name at all. Pass in the variable containing the control.
Comment: ok, almost there. Now I've got a statement for each DropDownList:TextBox pair, but it still not iterative. Can this be done, or do I have to call each pair separately? I'm afraid I'm gonna need some code if it's possible. I can't seem to figure it out. Thanks :)
Comment: Sorry, might you answer my last comment please? Then I'll mark it answered, Thanks. :)
Answer: I am not sure if the samething that applies VBA will apply to your situation, but I had the same issue and was able to use:
Me.MultiPage1.Pages(1).Controls("ref" & i + 1).Value
where controls encompasses all controls on the userform ("Me").  So if the controls in your program conform to a consecutive naming structure it is easy handle if the above applies vb.net


Having trouble finding downward acceleration of top of ladder in a standard, but tricky, ladder and wall problem

Question: An 18-foot ladder extends over a 12-foot wall; the bottom of the ladder is pulled away from the wall at 2'/sec; find the vertical velocity (then acceleration) of the top of ladder when the angle the bottom of the ladder makes with the floor = pi/3 (60 degrees.)  It's the acceleration, or second derivative of the 'y' value, that I'm having trouble with.
I posted this a few days ago with my attempted solution to the easier part, the downward velocity of the top of the ladder at the time in question.
I had apologized in advance for any errors ; now I'm apologizing retroactively as well. My solution was incorrect. I had failed to realize that though the length of the ladder itself was a constant (18'), the distance protruding over the top of the wall was changing, thus a variable (call it 'd') which needed to be accounted for.
(I am not sure how to upload a diagram, which would have been helpful)
Using the Pythagorean Theorem, some basic trig to find 'x' (the distance between the foot of the ladder and the wall) and '18-d' (the length of the ladder minus 'd') and two equations, I was able to derive the correct answer, which my text provided, but did not explain.
These are equations I used:
$ 12^2 + x^2 \ = \ (18-d)^2 \ \ \text{and} \ \   \frac{y}{d} \  = \ \frac{12}{18-d} \ \ . $
I found dd/dt to be 1, substituted it back in to the differentiation of the second equation, and derived the textbooks answer of dy/dt = - 1.125 or -9/8. So much for the velocity. Now, for the second part of the question, I'm stumped.
Does anyone know how to use these equations (or perhaps some other equation) to find y'', the downward acceleration?  Many thanks, as I'm trying to learn this on my own
(Note: the text in question is Calculus (6th edition) by Varberg and Purcell, 1992; P 155, Q 25.
Comment: Here's the link to learn how to use mathjax "https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference", when you type your questions it should be formatted like so. Also you want $\theta$ to be a variable and you want to find an equation that describes both $x$ and $y$ terms of $\theta$ (hint: use the $\sin$ and $\cos$ ratios), then use the chain rule.
Comment: I would do this with variables $x$ and $y$ only. You don't need anything else. You can write $y$ as a function of $x,$ or you can write an equation using $x$ and $y$ and some known constants. Differentiate with respect to $t$ to get $y'.$ Do it again to get $y''.$
Answer: If you had written down the related-rates equation for $ \ \frac{dy}{dt} \ $ versus $ \ \frac{dx}{dt} \ \ , $ it would have been quicker to proceed from there.  We can reconstruct it easily enough, however.
The "overhang" $ \ D \ $ of the ladder beyond the top of the wall forms a similar triangle to the rest of the ladder, so you obtained the equations $ \ 12^2 + x^2 \ = \ (18-D)^2 \ \ , \ \   12·D \  = \ y·(18 - D) \ \ , $ from which implicit differentiation produces
$$  x· \frac{dx}{dt} \ \ = \ \  -(18 - D)·\frac{dD}{dt} \ \ , \ \ 12·\frac{dD}{dt} \ \ = \ \ (18 - D)·\frac{dy}{dt} \ - \ y·\frac{dD}{dt} $$ $$ \Rightarrow \ \ \frac{dD}{dt} \ \ = \ \ \frac{18 - D}{12 + y}· \frac{dy}{dt} \ \ . $$
We would like to "be rid of" the rate $ \ \frac{dD}{dt} \ \ , $ so substitution gives us
$$ x· \frac{dx}{dt} \ \ = \ \  -  \frac{(18 - D)^2}{12 + y}· \frac{dy}{dt} \ \ = \ \ -  \frac{12^2 \ + \ x^2}{12 + y}· \frac{dy}{dt}  $$
by application of our "Pythagorean" equation.  We now need the current values of $ \ x \ $ and $ \ y \ \ : \ $ as we are given that the ladder is inclined $ \ 60º \ $ to the ground at the moment in question, we have $  \tan 60º \ = \ \sqrt3 \ = \ \frac{12}{x} \ \Rightarrow \ x \ = \ 4·\sqrt3 \ \Rightarrow \ 18 - D \ = \ \sqrt{12^2 + (4 \sqrt3)^2} \ = \ \sqrt{192} \ = \ 8·\sqrt3 $
$$ \Rightarrow \ \ y \ \ = \ \ \frac{12·(18 - 8 \sqrt3)}{8 \sqrt3} \ \ = \ \ 9 \sqrt3 \ - \ 12 \ \ \approx \ \ 3.59 \ \ .  $$
Our related-rates equation then yields
$$ (4 \sqrt3) \ · \ 2 \ \ = \ \  -  \frac{192}{12 \ + \ (9 \sqrt3 \ - \ 12)}· \frac{dy}{dt} $$ $$ \Rightarrow \ \  \frac{dy}{dt} \ = \ - \frac{(4 \sqrt3) \ · \ 2 \ · \ (9 \sqrt3)}{192} \ \ = \ \ -\frac{216}{192} \ \ = \ \ -\frac98 \ \ . $$
So we are able to confirm your results to this point.
For the accelerations, we need to differentiate the related-velocities equation with respect to time.  For that, it will be convenient to re-arrange it as
$$ \frac{d}{dt} \ [ \ x·(12 + y)· \frac{dx}{dt} \ ] \ \ = \ \  - \frac{d}{dt} \ [ \  (12^2 \ + \ x^2)· \frac{dy}{dt} \ ] $$
$$ \Rightarrow \ \  \frac{dx}{dt} ·(12 + y)· \frac{dx}{dt} \ + \ x·\frac{dy}{dt}· \frac{dx}{dt} \ + \ x·(12 + y)· \frac{d^2x}{dt^2}   $$ $$ = \ \  -  \ [ \ 2x · \frac{dx}{dt} · \frac{dy}{dt} \ + \ (12^2 \ + \ x^2)· \frac{d^2y}{dt^2} \ ] \ \ , $$
after extensive use of the Product and Chain Rules.  The problem statement suggests (it doesn't say so specifically) that $ \ \frac{dx}{dt} \ = \ +2 \ $ is constant, making $ \ \frac{d^2x}{dt^2} \ = \ 0 \ \ . $  Our work tells us that $ \ \frac{dy}{dt} \ = \ -\frac98 \ \ ,  $ $ x \ = \ 4·\sqrt3 \ \ , \ \ 12^2 \ + \ x^2 \ = \ 192 \ \ , \ \ \text{and} \ \ 12 + y \ = \ 9 \sqrt3 \ \ . $  So we may write
$$   (9 \sqrt3)· (2)^2 \ + \ (4 \sqrt3)·\left(-\frac98 \right)· 2 \ + \ 0   \ \  = \ \  -   \left[ \ 2·(4 \sqrt3)· 2 · \left(-\frac98 \right) \ + \ 192 · \frac{d^2y}{dt^2} \ \right]  $$
$$  \Rightarrow \ \  36 \sqrt3 \ - \ 9 \sqrt3 \ \  = \ \  18 \sqrt3 \ - \ 192 · \frac{d^2y}{dt^2} $$ $$ \Rightarrow \ \  \frac{d^2y}{dt^2} \ \ = \ \ -\frac{9 \sqrt3}{192} \ \ = \ \ -\frac{3 \sqrt3}{64} \ \ \approx \ \ -0.0812 \ \frac{\text{ft.}^2}{\text{sec.}} \ \ . $$
So the top of the ladder is undergoing a very small downward acceleration, largely owing to the fact that the angle the ladder makes to the ground is decreasing.


How to import pygame in gitpod?

Question: This is a simple SudokuSolver App.
Project on GitHub
It's working perfectly. But when I try to run it in gitpod it's unable to import pygame.
Error:
gitpod /workspace/SudokuVizualizationBacktracking $ /home/gitpod/.pyenv/versions/3.8.2/bin/python /workspace/SudokuVizualizationBacktracking/GUI.py
Traceback (most recent call last):
  File "/workspace/SudokuVizualizationBacktracking/GUI.py", line 1, in <module>
    import pygame
ModuleNotFoundError: No module named 'pygame'

Can you please help me out? Thanks You.
Comment: Online IDE's most likely doesn't support locally generated OpenGL contexts. Just a hunch.
Answer: In your .gitpod.yml you have configured the following init task:
$ pip3 install -r requirements.txt

Start your workspace by opening https://gitpod.io/#https://github.com/Deepak-dash007/SudokuVizualizationBacktracking and run this command in the terminal. You'll get the following output:
$ pip3 install -r requirements.txt
Collecting pygame
  Downloading pygame-1.9.6.tar.gz (3.2 MB)
     |████████████████████████████████| 3.2 MB 6.8 MB/s
    ERROR: Command errored out with exit status 1:
     command: /home/gitpod/.pyenv/versions/3.8.2/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-fgexue3e/pygame/setup.py'"'"'; __file__='"'"'/tmp/pip-install-fgexue3e/pygame/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-9lyba20o
         cwd: /tmp/pip-install-fgexue3e/pygame/
    Complete output (12 lines):

    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using UNIX configuration...

    /bin/sh: 1: sdl-config: not found
    /bin/sh: 1: sdl-config: not found
    /bin/sh: 1: sdl-config: not found

    Hunting dependencies...
    WARNING: "sdl-config" failed!
    Unable to run "sdl-config". Please make sure a development version of SDL is installed.
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Here you can see that sdl-config is missing. Google found this Stack Overflow answer that lists dependencies needed for pygame: https://stackoverflow.com/a/60990677/1364435
Change your image config in your .gitpod.yml to:
image:
  file: .gitpod.Dockerfile

and added a new file .gitpod.Dockerfile that installs the dependencies linked in the other Stack Overflow post:
FROM gitpod/workspace-full-vnc

RUN sudo apt-get update && sudo apt-get install -y \
    python-dev libsdl-image1.2-dev libsdl-mixer1.2-dev libsdl-ttf2.0-dev libsdl1.2-dev libsmpeg-dev python-numpy subversion libportmidi-dev ffmpeg libswscale-dev libavformat-dev libavcodec-dev

Push everything and create a new Gitpod workspace. That's it.
You'll find a running repo here https://github.com/corneliusludmann/SudokuVizualizationBacktracking
I also created a Pull Request for you: https://github.com/Deepak-dash007/SudokuVizualizationBacktracking/pull/1

How to import pygame in gitpod?


How do I call pathauto alias using php

Question: I have pathauto installed on my D7 setup along with all my taxonomy terms configured.
How do I then call the alias using PHP for custom code?
EDIT: just to clear things up - I want to output the alias URL that has been created and assigned to each specific node. For example:
Terms
- Country
- City
For node #1 an alias is created as {site}/[country]/[city]
I would like to output the alias that has been created for the node so I can visit for example {site]/england/london instead of {site}/node/1
Answer: If you mean the alias for the taxonomy term you can use url() (if you just want the URL), or l() if you want a link:
$url = url('taxonomy/term/' . $term->tid);

$link = l('Link text', 'taxonomy/term/' . $term->tid);

Both of those will give you the current path alias for the term page
Comment: also `$path = drupal_get_path_alias('taxonomy/term/' . $term->tid);` if all you want is the bare path.

How do I call pathauto alias using php


multiple nginx config files under nginx/conf.d/ and 404

Question: A seemingly very simple reverse proxy config is giving me headache here.
Main config file /etc/nginx/nginx.conf has
"include /etc/nginx/conf.d/*.conf;"
Then I have two conf files under conf.d:
default-1.conf and default-2.conf
First file has:
server {
  # HealthCheck
  server_name _;
  listen 0.0.0.0:443 ssl ;
  location = /health.html {
  root /usr/share/nginx/html;
 }
}

And second file has additional proxy statements as
server {

 listen 0.0.0.0:443 ssl ;

 server_name www.example2.com;
 ...
 location / {
 set $backend "some-backend";
 proxy_pass $scheme://$backend;
 }
}

When there is only default-1.conf is under conf.d/,
curl -k https://localhost/health.html works.
If I also put default-2.conf under conf.d/, then same curl command gives 404 Not Found. I don't see any error under error.log either.
What am I doing wrong?
How can I learn the rules applied during building final conf file using these multiple smaller conf files?
Thank you.
Answer: Your server_name _; doesn't make this a default catch-all server. From NGINX Server names:

In catch-all server examples the strange name _ can be seen:
server {
    listen       80  default_server;
    server_name  _;
    return       444;
}

There is nothing special about this name, it is just one of a myriad
  of invalid domain names which never intersect with any real name.
  Other invalid names like -- and !@# may equally be used.

And a bit further:

Note that there is no way to specify the catch-all name or the default
  server using the server_name directive. This is a property of the
  listen directive and not of the server_name directive.

Your default-1.conf should have:
server {
    # HealthCheck
    listen       0.0.0.0:443  ssl  default_server;
    server_name  _;

    location = /health.html {
        root /usr/share/nginx/html;
    }
}

Comment: That was it! Thank you for clearing server_name and listen directives for me.


jquery images align center on position absolute

Question: I need help in JQuery.
I have some div-elements with pictures of different sizes inside.
They are arranged in absolute position (bottom: 0). I want that only smaller images of the div container are positioned at the center (horizontal).
var image = $(".inner img");
var box = $('.inner').width();
var wimage = image.width();
var total = (box - wimage) / 2;

if(wimage <= 190 ){
   image.css('margin-left', total);
}

Fiddle for demo.
Thank you all for your support!
Answer: Is this what you were after?
http://jsfiddle.net/3XM66/1/
JS
$('.inner img').each(function () {
    var imgWidth = $(this).width();
    $(this).css('margin-left', imgWidth / 2 * -1);
});

Answer: $(".inner").each(function(){
var image = $(this).find("img");
var box = $(this).width();
var wimage = image.width();
var total = (box - wimage) / 2;
    if(wimage <= 190 ){
    image.css('margin-left', total);
}
});

Answer: should be like this:
var image = $(".inner img");

image.each(function(){
    var wimage = $(this).width();
    var box = $('.inner').width();
    var total = (box / 2) - (wimage / 2);

    //console.log(wimage);
    //console.log(box);
    //console.log(total);

    if(wimage <= 190 ){
       $(this).css('left', total);
    }
});

demo http://jsfiddle.net/jogesh_pi/3XM66/4/
Answer: $(".inner img").each(function(index, Element){
    var image = $(Element);
    image.css('margin-left', (image.parent().parent().width() - image.width())/2);
});

http://jsfiddle.net/3XM66/5/


How to capture NoClassDefFoundError

Question: I'm experiencing this issue when updating to the installreferrer library v2.0. LINK
So when I call to the library's startConnection method it throws:
Process: com.tomatedigital.lottogram, PID: 13424
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/aidl/BaseStub;
    at com.android.installreferrer.api.InstallReferrerClientImpl.startConnection(InstallReferrerClientImpl.java:36)
    at com.tomatedigital.lottogram.app.App.saveReferralInfo(App.java:221)
    at com.tomatedigital.lottogram.app.App.onCreate(App.java:102)
    at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1182)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6460)
    at android.app.ActivityThread.access$1300(ActivityThread.java:219)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1859)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

I think it is a bug in the library, since if you downgrade to previous versions it works great. I'd like to avoid this crash.
I've tried wrapping the code with a :
catch(Throwable ignore){}

But it keeps crashing. How can I gracefully handle this error?
Answer: Short answer: You cannot really gracefully handle this error.
Why? You are still trying to use some stuff out of this library, so it makes no sense in handling this error. Either you remove this library (because you don't need it) or the error itself (classpath issues) must be resolved.
Typically, exceptions like this are critical and you should not try to handle it, because you have a serious error.
Comment: I don't say he should not use the library, I just say that if he wants to use the library, then the classpath issues must be resolved. And that is the reason why there is no point in catching this exception, because if this exception rises, then the library he wants to use can obviously not be used due to those issues...
So, the question was "how to gracefully handle this error?". And my answer is, that it is not really possible and reasonable to handle this error. Sure, it does not resolve the lib problem (I don't know the lib), but I wouldn't consider my answer "totally useless"....
Comment: I can't fix the classpath since it is a transitive dependency of the library :(

How to capture NoClassDefFoundError


Extract BIC and AICc from arima() object

Question: Problem: I would like to extract the BIC and AICc from an arima() object in R.
Background: The arima() function produces an output of results, which includes the estimated coefficients, standard errors, AIC, BIC, and AICc. Let's run some sample code to see what this looks like:
# Load the sunspots dataset
data(sunspots)
# Build an ARIMA(2,0,2) model and store as an object
model <- arima(x=sunspots, order=c(2,0,2), method="ML")
# Show a summary of the model
model

The output of results for the model appears like this:
Series: sunspots
ARIMA(2,0,2) with non-zero mean

Coefficients:
         ar1     ar2      ma1      ma2  intercept
      0.9822  0.0004  -0.3997  -0.1135    51.2652
s.e.  0.1221  0.1196   0.1206   0.0574     8.1441

sigma^2 estimated as 247.9:  log likelihood=-11775.69
AIC=23563.39   AICc=23563.42   BIC=23599.05

On the bottom line, we can see values for AIC, BIC, and AICc. (Note: this is the output shown by arima() when the forecast package has been loaded, i.e. library(forecast))
Accessing the AIC value is quite easy. One can simply type:
> model$aic
[1] 23563.39

Access to the AIC value in this manner is made possible due to the fact that it's stored as one of the model's attributes. The following code and output will make this clear:
> attributes(model)
$names
 [1] "coef"      "sigma2"    "var.coef"  "mask"      "loglik"
 [6] "aic"       "arma"      "residuals" "call"      "series"
[11] "code"      "n.cond"    "model"

$class
[1] "Arima"

Notice, however, that bic and aicc are not model attributes, so the following code is no use to us:
> model$bic
NULL
> model$aicc
NULL

The BIC and AICc values are, indeed, calculated by the arima() function, but the object that it returns does not give us direct access to their values. This is inconvenient and I've come across others who've raised the issue. Unfortunately, I've not found a solution to the problem.
Can anyone out there help? Which method can I use to access the BIC and AICc from the Arima class of object.
Note: I've suggested an answer below, but would like to hear improvements and suggestions.
Edit (Version details as requested):
> R.Version()
$platform
[1] "i686-pc-linux-gnu"

$arch
[1] "i686"

$os
[1] "linux-gnu"

$system
[1] "i686, linux-gnu"

$status
[1] ""

$major
[1] "3"

$minor
[1] "0.2"

$year
[1] "2013"

$month
[1] "09"

$day
[1] "25"

$`svn rev`
[1] "63987"

$language
[1] "R"

$version.string
[1] "R version 3.0.2 (2013-09-25)"

$nickname
[1] "Frisbee Sailing"

Comment: @Glen_b I think I understand the problem with the arima output that you encountered. The forecast package had been loaded on my machine and this has the effect of changing the output of the arima() function! Not ideal behaviour and I only noticed it today, myself. Not loading the forecast package and calling arima() returns only the aic in the output - not the BIC and AICc. Compare the outputs when the forecast package is loaded and not loaded to see what I mean. Apologies for not pointing this out earlier - I've now added a note to my answer to highlight the issue.
Comment: Which version of R is this? 3.0.2?
Comment: See edit. @Glen_b
Comment: Feel free to edit and trim down the details if you like. Wasn't sure how much detail you wanted. :)
Comment: Well, for myself I was just after the version number in the interest of checking the code for arima (the machine I was on at the time didn't reproduce the suggested behavior; it had an older version of R), but since this is intended to be a permanent repository and future versions of R will continue to change the behavior, it's hard for me to be sure what parts to take out. Someone more knowledgeable than me might be better at guessing what won't ever be relevant.
Answer: For the BIC and AIC, you can simply use AIC function as follow:
> model <- arima(x=sunspots, order=c(2,0,2), method="ML")
> AIC(model)
[1] 23563.39
> bic=AIC(model,k = log(length(sunspots)))
> bic
[1] 23599.05

The function AIC can provide both AIC and BIC. Look at ?AIC.
Comment: Ah! Excellent! I had tried the AIC() and BIC() functions! I wasn't aware that the AIC() function could provide the BIC. Thanks very much, @Stat! This method saves a whole lot of bother.
Answer: Answer:
One possible solution, although no claim to be the best, is as follows; it's a hack that I've come up with after looking at some source code.
npar <- length(model$coef) + 1
nstar <- length(model$residuals) - model$arma[6] - model$arma[7] * model$arma[5]

bic <- model$aic + npar * (log(nstar) - 2)
aicc <- model$aic + 2 * npar * (nstar/(nstar - npar - 1) - 1)

Now that the bic and aicc have been stored as objects - using, solely, output from the arima() function - we can now set them as attributes to the model object.
# Give model attributes for bic and aicc
attr(model,"bic") <- bic
attr(model,"aicc") <- aicc

> attributes(model)
$names
 [1] "coef"      "sigma2"    "var.coef"  "mask"      "loglik"
 [6] "aic"       "arma"      "residuals" "call"      "series"
[11] "code"      "n.cond"    "model"

$class
[1] "Arima"

$bic
[1] 23599.05

$aicc
[1] 23563.42

Pass on these attributes to a new object (we don't want to overwrite model).
# Create new object with these attributes
model_2 <- attributes(model)

We can now access the BIC and AICc in a similar manner as to how we accessed the AIC value. The following code should make this clear:
> model$aic
[1] 23563.39
> model_2$bic
[1] 23599.05
> model_2$aicc
[1] 23563.42

Edit:
Based on the very useful information provided by @Stat about the AIC() function, the following code may be useful as alternative ways of getting the AIC, BIC, AICc, and HQC. Attach them as attributes to the model object and work away.
# AIC
AIC(arima(x=sunspots, order=c(2,0,2), method="ML"))
# BIC
AIC(arima(x=sunspots, order=c(2,0,2), method="ML"),k=log(length(sunspots)))
# AICc
AIC(arima(x=sunspots, order=c(2,0,2), method="ML")) + 2 * npar * (nstar/(nstar - npar - 1) - 1)
# HQC
AIC(arima(x=sunspots, order=c(2,0,2), method="ML"), k=2*log(log(length(sunspots))))

Comment: This answer, rather than the ones that merely call built-in black-box functions, is the one that actually is informative and of interest on this site.
Answer: Here is a function my TA in my time series analysis course at UC Davis wrote to extract the AICc
Function aicc() computes the AICc of a given ARIMA model.
INPUT: an ARIMA model object produced by arima()
OUTPUT: AICc value for the given model object
aicc = function(model){
n = model$nobs
p = length(model$coef)
aicc = model$aic + 2*p*(p+1)/(n-p-1)
return(aicc)
}

Example:
x = arima.sim(100,model=list(ar=(0.3)))
mod = arima(x,order=c(1,0,0))
aicc(mod)

Answer: Once you have loaded forecast package, you must use Arima() function for AIC, AICc and BIC. Notice upper "A" in Arima() function. If you use arima() function with lower "a", then R will use the function that comes with base R.
Comment: Are you suggesting there is a typo in his code which does show them after sue of arima?
Answer: what it seems like is you are using incorrect arima function to get the values. Note that, arima() is not part of forecast library, you will have to use Arima() instead.
once the library(forecast) is imported use below function to extract the values:
model=Arima(grow, order=c(2,0,0))
attributes(model)
$names
[1] "coef"      "sigma2"    "var.coef"  "mask"      "loglik"    "aic"
 [7] "arma"      "residuals" "call"      "series"    "code"      "n.cond"
[13] "nobs"      "model"     "aicc"      "bic"       "x"
$class
[1] "ARIMA" "Arima"
model$bic
[1] 1069.786
model=arima(grow, order=c(2,0,0))
attributes(model)
$names
[1] "coef"      "sigma2"    "var.coef"  "mask"      "loglik"    "aic"
 [7] "arma"      "residuals" "call"      "series"    "code"      "n.cond"
[13] "nobs"      "model"
$class
[1] "Arima"
Hope this helps.. :)


What happens to adjusted R squared as sample size increases?

Question: What effect does sample size have on adjusted R squared values?
Comment: My first intuition is all things being equal, there is no effect.
Answer: Adjusted r-squared is intended to be an unbiased estimate of population variance explained using the population regression equation. There are several different formulas for adjusted r-squared and there are various definitions of population variance explained (e.g., fixed versus random-x assumptions). Most commonly, statistical software will report the Ezekiel formula which makes the fixed-x assumption.
In general, as sample size increases,

the difference between expected adjusted r-squared and expected r-squared approaches zero; in theory this is because expected r-squared becomes less biased.
the standard error of adjusted r-squared would get smaller approaching zero in the limit.

So the main take-home message is that if you are interested in population variance explained, then adjusted r-squared is always a better option than r-squared. That said, as your sample size gets very large, r-squared won't be that biased (note that for models with large numbers of predictors, sample size needs to be even bigger for r-squared to approach being unbiased).
Answer: Here's a simple function in R that simulates two Gaussian variables and copies them to inflate sample size without changing their correlation. It plots adjusted $R^2$ over increasing copies with a line at $R^2$.
Adj.R.Squared=function(Sample.Size=10,Max.Copies=30,Noise=1){Adj.R²=c();y=rnorm(Sample.Size)
x=y+Noise*rnorm(Sample.Size);Copies=1:Max.Copies;for(i in 1:Max.Copies)
{Adj.R²=append(Adj.R²,summary(lm(rep(y,i)~rep(x,i)))$adj.r.squared)}
plot(Copies,Adj.R²);abline(h=summary(lm(y~x))$r.squared,col='red');lines(Copies,Adj.R²)
legend('bottomright',c('Adj. R²','R²'),lty=1,col=c('black','red'),pch=c(1,NA))}

It generates new data every time you run it, but always takes on more or less the same shape, asymptotically approaching $R^2$ like @JeromyAnglim described. For example, with set.seed(1):

Decreasing Noise (which increases $R^2$) will shrink the scale of the $y$ axis but not alter the shape: i.e., the difference between adjusted $R^2$ and $R^2$ decreases as $R^2$ increases, but doesn't change the effect of sample size. Increasing Sample.Size makes adjusted $R^2$ approach $R^2$ a little more slowly, but mostly shrinks the scale of the $y$ axis. You can increase Max.Copies to extend the $x$ axis, or modify this function to work with manually entered data or multiple predictors. I've done this myself but not included the code because it doesn't seem to change the basic conclusion. This is intended as a maximally simple answer to a very simple question. Therefore its generalizability may be limited.


Power Series ODE Question - Final Step

Question: I just started learning how to use the power series method to solve ordinary differential equations and this is one of the first questions we were asked. I've managed to get it right up to the last step (assuming I've made no silly errors which I don't think I have as my final line of maths is similar to the solution of the problem set). But I'm not sure how to get to the final solution from the working I have.
The question is as follows:
$$(2x-x^2)y''+(x-1)y'+3y=0, \;\;\;\; y(1)=1, \;\;\;\;  y'(1)=1$$
I have my solution written in the form:
$$y(x) =\sum_{k=0}^{\infty}a_k(x-1)^k$$
and have come to the conclusion that:
$$a_{k+2}=\frac{k^2+3}{(k+2)(k+1)}a_k$$
so:
$$a_0=1$$
$$a_1=1$$
$$a_2=\frac{3}{2}$$
$$a_3=\frac{4}{3\cdot2}$$
$$a_4=\frac{21}{4\cdot3\cdot2}$$
$$a_5=\frac{48}{5\cdot4\cdot3\cdot2}$$
$$a_6=\frac{399}{6\cdot5\cdot4\cdot3\cdot2}$$
$$a_7=\frac{1344}{7\cdot6\cdot5\cdot4\cdot3\cdot2}$$
Happy to be corrected here but my main issue is how they got from these values to the final solution of:
$$y(x) = 1+3\left[-\frac{1}{2!!}(x-1)^2+\frac{1}{4!!}(x-1)^4+\sum_{k=3}^{\infty}\frac{(2k-5)!!}{(2k)!!}(x-1)^{2k}\right]+\left[(x-1)+\frac{2}{3}(x-1)^3\right]$$
I could go ahead and just expand the bottom and see how they're the same but I have no idea how I would've gotten numbers that look as arbitrary (to me at least) as 399 and 1344 to come together as the argument in the summation.
Any help is super appreciated!
Answer: Your equation is
$$
0=[(x-1)^2-1]y''-(x-1)y'-3y
$$
leading to the coefficient relation at $(x-1)^k$
$$
0=[k(k-1)-k-3]a_k-(k+2)(k+1)a_{k+2}=(k+1)[(k-3)a_k-(k+2)a_{k+2}]
$$
Thus the corrected coefficient recursion is
$$
a_{k+2}=\frac{k-3}{k+2}a_k
$$
At $k=3$ one finds $a_5=0$ so that $a_{2k+1}=0$ for $k>1$. In the even index sequence then one has
$$
a_{2(k+1)}=\frac{2k-3}{2(k+1)}a_{2k}\iff a_{2k}=\frac{2k-5}{2k}a_{2(k-1)}
$$
which then leads to the double factorial formulas for the coefficients.
Comment: Now give it also a positive *sigh* or two as the work on this task is done.
Comment: After all that my mistake was not distributing a negative *sigh*. Honestly, I had tried a fair few times and apparently kept making the same mistake so thanks for giving me the kick I needed to find it!! super helpful :)

Power Series ODE Question - Final Step


Proof of Cauchy Integral Formula using homotopy of curves

Question: This is from Stein and Shakarchi.

Give another proof of the Cauchy integral formula
$f(z)=\frac{1}{2\pi i}\int_C \frac{f(\zeta)}{\zeta-z}d\zeta$
using homotopy of curves.
(Hint: Deform the circle $C$ to a small circle centered at $z$, and
note that the quotient $\frac{f(\zeta)-f(z)}{\zeta-z}$ is bounded)

I found other posts about this problem but I couldn't find the answer to my question.
I found that the problem reduces to the problem of showing that $\frac{1}{2\pi i}\int_{C_r} \frac{f(\zeta)}{\zeta-z}d\zeta$ approaches to zero as $r$ goes to zero. I think this is where I need to use the theorem of homotopy in the book (integrals over holomorphic function on two path-homotopic curves is same). But since end points of different circles are not exactly the same, they are not path-homotopic. How can I modify the theorem to apply it in the problem?
Comment: Maybe page 46 of this compendium can be of help: https://www.maths.usyd.edu.au/u/olver/teaching/MATH3964/cauchy.pdf
Comment: Thank you but I am specifically looking for the proof using homotopy of curves
Comment: Also observe that closed contours do not have to have the same starting points in order to be homotopic.
Answer: Let $C$ be circle centered at $z_0$ and let $C_r$ be a circle centered at $z_0$ contained within $C$. We consider
$$\frac{1}{2\pi i} \int_{C} \frac{f(\zeta)}{\zeta-z_0}d\zeta = \frac{1}{2\pi i} \int_{C} \frac{f(\zeta)-f(z_0)}{\zeta-z_0}d\zeta + \frac{f(z_0)}{2\pi i} \int_{C} \frac{1}{\zeta-z_0}d\zeta$$
Now, observe that $C$ can be continously deformed into $C_r$. Thus, we have
$$\frac{1}{2\pi i} \int_{C} \frac{f(\zeta)}{\zeta-z_0}d\zeta=\frac{1}{2\pi i} \int_{C_r} \frac{f(\zeta)-f(z_0)}{\zeta-z_0}d\zeta + \frac{f(z_0)}{2\pi i} \int_{C_r} \frac{1}{\zeta-z_0}d\zeta$$
Now, we prove that the first integral approaches zero as $r \rightarrow 0$:
$$\bigg| \int_{C_r} \frac{f(\zeta)-f(z_0)}{\zeta-z_0}d\zeta \bigg| \leq \int_{C_r} \bigg|\frac{f(\zeta)-f(z_0)}{\zeta-z_0} \bigg| d \zeta \leq M \ell(C_r)=2\pi Mr \rightarrow 0$$
when $r \rightarrow 0$. The last integral is equal to $f(z_0)$, which proves the theorem.
Comment: Yes, to be homotopic and to be continous deformations of each other is two ways of saying the same thing.
Comment: Just to make sure, $C$ being continuously deformed into $C_r$ is the part where we want to use homotopy theorem, is this correct?
Answer:
The integrals along $a$ and $b$ cancel as they are the same line in opposite directions.  Thus the integral around $C_r$ is the same as the integral along the path $aC_rb$, which is homotopic to the path $C_1$.
Answer: The way that I did is the following:
Because of continuity, $\dfrac{f(w)-f(z)}{w-z}$ is bounded, then $w-z$ is a removable singularity, so $\dfrac{f(w)-f(z)}{w-z}$ has primitive and $$\int_C \dfrac{f(w)-f(z)}{w-z}dw=0,$$
the result follows by calculating $\int\frac{dw}{w-z}$.


Is a PrintWriter a BufferedWriter

Question: Basically I would like to know whether or not the PrintWriter is a Buffered Writer.
I have seen code like PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
However from this javadoc:

Parameters:
      file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new
  file will be created. The output will be written to the file and is
  buffered.

Bottom line: I think that PrintWriter is buffered since the javadoc "kind of mention it" (see the quote) and if I don't flush a PrintWriter it does not get printed.
Do you confirm my thesis? In that case why there is some code that goes like:
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
legacy code?
Thanks in advance.
Answer: Technically, it is not a BufferedWriter.  It directly extends Writer.  That said, it seems like it can use a BufferedWriter depending on the constructor you call.  For exampe look at the constructor that passes in a String:
public PrintWriter(String fileName) throws FileNotFoundException {
    this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
         false);
}

Also, you're not using the constructor for the javadoc you've linked to.  You've used the constructor that takes a Writer.  That one does not seem to use a BufferedWriter.  This is its source code:
/**
 * Creates a new PrintWriter, without automatic line flushing.
 *
 * @param  out        A character-output stream
 */
public PrintWriter (Writer out) {
    this(out, false);
}

/**
 * Creates a new PrintWriter.
 *
 * @param  out        A character-output stream
 * @param  autoFlush  A boolean; if true, the <tt>println</tt>,
 *                    <tt>printf</tt>, or <tt>format</tt> methods will
 *                    flush the output buffer
 */
public PrintWriter(Writer out,
                   boolean autoFlush) {
    super(out);
    this.out = out;
    this.autoFlush = autoFlush;
    lineSeparator = java.security.AccessController.doPrivileged(
        new sun.security.action.GetPropertyAction("line.separator"));
}

Comment: Ok so if constructed with a file/fileName it uses a BufferedWriter implicitly otherwise it has to be declared in the constructor?
Comment: Not exactly.  It really depends on the constructor you use.  You have to look at the source to be sure, or you can always create it like you did above and not have to think about it.
Comment: Why making it autoflushable if not buffered then?

Is a PrintWriter a BufferedWriter


This intersection has at most 2 components

Question: Let $U$ and $V$ two sets homeomorphic either to the open interval (0,1) or the half-open interval [0, 1), then their intersection has at most two components.
My attempt was show that the open connect sets in the real line are the open intervals ones. The problem is the intersection of open subsets has at most one component. Anyone can help me in this part?
Thanks
Comment: I take it that $U$ and $V$ are subsets of $\Bbb R$? Because it's not true without some such restriction.
Comment: @BrianM.Scott I think yes, U and V are subsets of $\mathbb R$, in fact I'm studying this classification theorem for 1-manifolds: http://www.igt.uni-stuttgart.de/eiserm/lehre/2010/Topologie/Gale%20-%201-manifolds.pdf and I'm stuck in a corolary.
Comment: Do you really mean union? Because for intervals one can get cases where union has two components, and other cases where union has one component (overlap of intervals). If it's intersection as you have it, then you can't get two components anyway.
Comment: Let the two intervals be $(a,b),(c,d)$ (since sets homeomorphic to $(0,1)$ or $(0,1]$ must be connected, and a connected subset of the reals is an interval). To save cases I'm using round brackets everywhere, but one can keep in mind that one or two of the round brackets could be replaced by square ones, in various orders. I of course am also assuming $a<b$ and $c<d$ since otherwise the intervals are empty. The "point" intervals $[c,c]$ are excluded as the initial intervals by your homeomorphic assumption, however one such might appear as an intersection, for example with $(-1,0]\cap[0,1)$.
Comment: Now consider the possible orderings of the four points $a,b,c,d$ on the number line. (as usual an endpoint can be $+\infty$ or $-\infty$ on the intervals, and we use the usual convention for finite $c$ that $-\infty<c<+\infty$.

You'll find that in all cases the intersection has only one component, or else is empty ($0$ components).
Answer: Seeing the paper changes things completely. $U$ and $V$ are not (necessarily) subsets of $\Bbb R$; they're subsets of a manifold $X$ that are homeomorphic (via maps $\varphi$ and $\psi$, respectively) to $(0,1)$ or $[0,1)$. And yes, $U\cap V$ can have two components: let $X$ be the unit circle in the plane, let $U$ be the set of points of $X$ whose polar coordinates are $\langle 1,\theta\rangle$ for $-\frac{\pi}4<\theta<\frac{5\pi}4$, and let $V$ be the set of points of $X$ whose polar coordinates are $\langle 1,\theta\rangle$ for $\frac{3\pi}4<\theta<\frac{9\pi}4$. Then the intersection of $U$ and $V$ consists of two disjoint open arcs of $X$.
Have you tried to prove Proposition 1 following the hint given?
Comment: @user42912: The connected sets in $\Bbb R$ are the intervals; they don't have to be open. And showing that $\varphi[W]$ and $\psi[W]$ are open intervals isn't enough anyway: you have to show that they are **outer** intervals.
Comment: I thought (since the "attempt outlined in the question mentioned looking at the real line), that the space was the set of reals. As B. Scott's remark shows, intersection can have 2 components on the 1-manifold of the unit circle. And of course for higher dimensional manifolds there can be any number of components.
Comment: yes, I proved the proposition 1, but differently. I proved saying that since ψ and ϕ are homeomorphisms, then ϕ(W) and ψ(W) are connected. The connected sets in the real line are the open intervals, thus ϕ(W) and ψ(W) has to be open intervals.
Comment: I tried to do the same strategy to prove the corollary, but it didn't work.


Identify test GooglePlay purchases

Question: I have three different subscription purchases with different duration. I've configured test accounts and I can do test purchases. For those purchases Google doesn't charge me, but they look pretty much like real ones. When purchase is successfull, In-App Billing sends me some data about my purchase like packageName, productId, orderId, purchaseToken and so on.
In my handling code I need to know somehow if this purchase is real or not. In plain text: did I really earn money for it or was this purchase made by some test account and I earned for it nothing? I need this kind of info for purchases accounting.
So the question is: How do I distinguish between real and test subscription purchases in code?
Thanks.
P.S. I'm using Xamarin and C# for development.
Comment: I'm not sure I 'fully' understand your question, but on the physical device we used the fact the we are tagging the apk release version as an 'alpha' or 'beta' and thus those versions are only used by testers that have opted-in to the alpha/beta program (alpha=internal testers, beta = external testers for us at least), thus live apps = real $. Thus when we forward (from the phone) to our servers that a purchase was made, those records with this extra info and also save them with a `14-day` test flag as the order will be cancelled at that point.  lol, I'm close to want you are trying to do?
Comment: Yes, kind of. But here are two questions: can I somehow make a real purchase on alpha/beta version? can I somehow make test purchase on production app version?
Comment: Ahh, got it now, and yes, random's answer is what was done on one project for 'real' users...
Answer: You can make real purchase on a alpha/ beta version if your account is not added to licensed accounts list in your Google Play developer account.
Check this:

With alpha/beta test groups, real users (chosen by you) can install
  your app from Google Play and test your in-app products. They can make
  real purchases that result in actual charges to their accounts, using
  any of their normal payment methods in Google Play to make purchases.
  Note that if you include test license accounts in your alpha and beta
  distribution groups, those users will only be able to make test
  purchases.

UPDATE
To know which purchase is real and which is test one, check for orderId in response. No orderId will be assigned for test purchases.
Issue with Android IAP, no OrderID in Purchase Object
Comment: Yes, exactly. So on alpha/beta versions it is possible to make both real and test purchases. And the same thing for production version. And my question is: how do I know which purchase is real and which is test one?
Comment: Damn, that easy? They should have written this with caps lock somewhere in documentation.. I'll try. Thanks!
Comment: Yes, you are right. Test purchases doesn't have `orderId`. Thanks.
Comment: "To know which purchase is real and which is test one, check for orderId in response. No orderId will be assigned for test purchases." <== This is no longer true. Test orderId purchases now have the same orderId as regular purchases. (my team used the same method, and is looking for a different solution to that now)
Answer: On the latest v3 Android Publisher API, you can obtain a SubscriptionPurchase object provided you have the Package name, SubscriptionId and the Token.
The SubscriptionPurchase object contains an optional (null-able) integer field named purchaseType. According to Google, when it is set and the value is 0, this is a Test subscription. I can confirm this works and matches the data I am getting back.
Here is the quote from Google's documentation:
    //     The type of purchase of the subscription. This field is only set if this purchase
    //     was not made using the standard in-app billing flow. Possible values are: 0.
    //     Test (i.e. purchased from a license testing account) 1. Promo (i.e. purchased
    //     using a promo code)

Identify test GooglePlay purchases


Array push in multidimensional array also pushing in array

Question: I'm using array_push to add values to a multidimensional array.
My code looks like:
foreach($arr as $key => $subArr){
  $tmp[$key] = array();

  foreach($subArr as $value){
    foreach($filter as $prod){
      if($prod['key_value'] == $key."_".$value){
        echo "array_push(tmp[{$key}], {$prod['id']})
";
        array_push($tmp[$key], $prod['id']);
      }
    }
  }
}

$arr holds:
Array
(
    [4] => Array
        (
            [0] => 821
        )

)

$filter is to big to post here, but it's an array with product ID's and the filter key key_value.
Now when I run this code, it's output is:
array_push(tmp[4], 180)
array_push(tmp[4], 172)
array_push(tmp[4], 182)
array_push(tmp[4], 116)
array_push(tmp[4], 170)
array_push(tmp[4], 169)
array_push(tmp[4], 144)
array_push(tmp[4], 145)
array_push(tmp[4], 187)
array_push(tmp[4], 124)
array_push(tmp[4], 198)
array_push(tmp[4], 148)
array_push(tmp[4], 163)
array_push(tmp[4], 195)
array_push(tmp[4], 194)
array_push(tmp[4], 196)

The $tmp array however looks like this:
Array
(
    [0] => 180
    [1] => 172
    [2] => 182
    [3] => 116
    [4] => Array
        (
            [0] => 180
            [1] => 172
            [2] => 182
            [3] => 116
            [4] => 170
            [5] => 169
            [6] => 144
            [7] => 145
            [8] => 187
            [9] => 124
            [10] => 198
            [11] => 148
            [12] => 163
            [13] => 195
            [14] => 194
            [15] => 196
        )

    [5] => 169
    [6] => 144
    [7] => 145
    [8] => 187
    [9] => 124
    [10] => 198
    [11] => 148
    [12] => 163
    [13] => 195
    [14] => 194
    [15] => 196
)

All productID's should be in tmp[4], but why are they also just in tmp?
Comment: Could you show a couple values inside `$filter`?
Comment: I don't think the issue is in the code that you have shown. Are you sure that `$tmp` itself is empty when you start?
Comment: The problem was that `$tmp` was not an array!
Answer: This is not really an answer, but it was too big for a comment.
I don't know why or how, but your $tmp contained the following when your loop started:
Array
(
    [0] => 180
    [1] => 172
    [2] => 182
    [3] => 116
    [4] => 170
    [5] => 169
    [6] => 144
    [7] => 145
    [8] => 187
    [9] => 124
    [10] => 198
    [11] => 148
    [12] => 163
    [13] => 195
    [14] => 194
    [15] => 196
)

Make sure that $tmp is an empty array when you start.
Comment: That was the fix. Just missed it!


Programmatically find out what fieldset a field belongs to, if any

Question: There doesn't seem to be a way to join the fieldset table in the database to a fields table, nor any function that can be used to get fieldset info by field name. Is there a way to get fieldset info starting from a single field's information (as well as bundle and such)?
Answer: If you call field_group_info_groups with the entity type and bundle, it will return all the field groups on the bundle, the fields should be in the children array under ['form'][YOUR_FIELDGROUP] e.g.
     $fieldgroups = field_group_info_groups('node', "YOUR_NODETYPE");
     $field_names = $fieldgroups['form']['YOUR_FIELDGROUP']->children;

$fieldnames should now contain a list of all the fields that pertain to YOUR_FIELDGROUP. Which you can now parse through using a foreach loop.
     $node = node_load(2);
     foreach ($field_names as $key => $field_name) {
      $field_items = field_get_items('node', $node, $field_name);
      // Do something cool here.
     }

Comment: Here's the docs page for this... http://api.drupalhelp.net/api/field_group/field_group.module/function/field_group_info_groups/7


Erro "invalid input '..' in utf8towcs" com o "read.csv"

Question: Tenho um banco de dados em .csv que reúne postagens tanto do Facebook quanto do twitter.
Para a leitura do banco em R, o código que tenho usado é
 bancodedados <- read.csv("nomedobanco.csv", sep=";", encoding="UTF-8")

O código carrega o banco de dados quase até o final, só que um erro interrompe a leitura:

invalid input 'RT @jmlara02: @LizCorreaa Camarada defina multicentrico camarada. 👉 @90Javier @NicolasMaduro' in 'utf8towcs'

Fazendo uma busca na internet, vi que o problema é, de certa forma, recorrente. Ele é causado pelo não reconhecimento de caracteres previsto no meu código (UTF-8), que, no caso, é "👉".
Algumas propostas de solução vista na internet:

Manualmente retirar os caracteres da base original._No caso, eu
descartei essa hipótese porque o banco de dados é bem grande e a
memória RAM do computador não tão grande.
Usar a função tryCatch(), o "error handling" do R, ignorar esse
erro e prosseguir com a leitura. Achei essa a melhor hipótese, só que
o uso do código é bastante não amigável. Tentei o pacote "debug" do
CRAN...também não achei muito melhor que o default.
Carregar, através do pacote "tm" do CRAN para o VCorpus. Realmente consegui carregar o banco e dados por essa via, no entanto ele não veio no formato dataFrame, ou seja...era o ,csv puro ali.

Portanto, a pergunta que fica é:
Seria a solução 2 a melhor, mesmo? Caso sim, como implementar o tryCatch junto com o read.csv para ignorar o erro e finalizar a leitura do banco de dados?
Se alguém possuir um manual de "Error handling" em português pode ajudar, também, rs.
Alguns links do problema :
https://stackoverflow.com/questions/26143270/read-umlaut-from-csv-file-in-rattle
http://minimalr.com/2013/01/06/tolower-error-catching-unmappable-characters/
https://stackoverflow.com/questions/9637278/r-tm-package-invalid-input-in-utf8towcs
Comment: Essa questão de encoding sempre é complicada. Sem ver os dados é difícil dar uma resposta certa, mas provavelmente algo nas seguintes linhas funcionaria: (i) leia o csv usando `readLines()`. Isso vai gerar um grande objeto de texto no R. (ii) converta o texto para o encoding correto usando `iconv()`. (iii) converta para data.frame usando `read.table(text = objeto_que_voce_criou_com_readLines)`. Isso deve funcionar.
Comment: Tu já tentou salvar em .txt e carregar pro dataframe? Se lembre de colocar o enconding UTF-8. Forneça um pequeno exemplo do arquivo para poder repetir a situação.
Comment: Eric, a sugestão acima funcionou, você conseguiu resolver o problema?
Answer: Olá! Eu costumo utilizar o file.choose() para eu mesmo selecionar o arquivo.
install.packages("dplyr")
library(dplyr)

dados = read.csv2(file.choose(), header = T)
print(dados)

O read.csv2 já separa o csv em ";" e o T ou F é para definir a "cabeça" do banco de dados.
Espero que tenha ajudado.
Answer: permita-me 'upar' o tópico com uma possível solução.
Tente o seguinte:
install.packages('stringr')
txt.tmp <- str_replace_all(conteudo_do_tweet,"[^[:graph:]]", " ")

A chamada acima remove os conteúdos gráficos existentes no tweet.
Comment: Jhonatas, sua resposta não resolve o problema diretamente porque o AP não conseguiu carregar os dados no R. Talvez seja uma solução em conjunto com a sugestão do Carlos nos comentários, mas a pergunta não pode ser testada sem um exemplo de dados reprodutível.
Comment: Hmmm, de fato. Entendi o que quis dizer. Poderia tentar essa solução na aplicação que gera o CSV, talvez. De qualquer forma, acho que o Eric desistiu ou ja encontrou a solução do problema.. hehe


HERE Maps Truck Api

Question: I have a truck routing API call for HERE maps. It splits the section into 3 parts including ferry section. However, I want to avoid receiving the route if route for the specified transport Mode is not available for HERE Routing API version 8.6.4 . Is there any parameter we can pass to avoid getting ferry route if truck is specified as transport mode?
Comment: I'm a bit confused. Are you saying you call the API and it returns a part that isn't available?
Comment: If you just want to avoid ferry, you can try add "&avoid[features]=ferry" to your API call. Please let us know if this will work.
Comment: Thanks for the reply. If i i add avoid ferry, it gives me the route with ferry with a notification that this route will violate the restrictions.However, I don't want any route if it involves any other mode of transport.
Answer: Unlike V7, V8 routing only supports "soft" avoid.
"Sometimes no route is possible that avoids the feature, for example specifying avoid[features]=ferry to an otherwise inaccessible island. In this case, a route is returned that makes minimal use of the feature. Furthermore, a notice is included to indicate that the route does not avoid the feature."
For details, you make check here.
Comment: It appears appending avoid[features]=ferry results in a "missing waypoints" error even when they are present.  See bug here:

No error: https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey=API_KEY_GOES_HERE&waypoint0=geo!44.648077,-63.571564&waypoint1=geo!46.329902,-62.362851&mode=fastest;car

With error: https://route.ls.hereapi.com/routing/7.2/calculateroute.json?apiKey=API_KEY_GOES_HERE&waypoint0=geo!44.648077,-63.571564&waypoint1=geo!46.329902,-62.362851&mode=fastest;car&avoid[features]=ferry

HERE Maps Truck Api


Laravel 5.5 Rotas?

Question: Não consigo achar o arquivo routes.php no Laravel 5.5 não esta dentro da pasta http só tem la dentro
http > controller/middleware/kernel

e isso que tem la dentro?
Comment: Não estará à procura do `routes/web.php` ?
Comment: Sempre bom ler a documentação do que está usando.
Answer: Você deve estar utilizando documentação/tutoriais de versões anteriores. 5.4 em diante os arquivos de rotas ficam na pasta "routes". Veja em Routing - Laravel. Nesse caso, você deve acessar a pasta routes/web.php para rotas de páginas .php

Laravel 5.5 Rotas?


Cauchy integral formula with a singularity inside the set

Question: Im struggling a bit with a Cauchy integral formula exercise.
Compute $\int_{C(0,4)} \frac{e^z}{z(z-3)} dz$
In past exercises i've been able to manipulate the integral to not have any singularities for $f(z)$, which is not the case in this one.
I dont really know how to proceed, since no-singularities is one of the criteria of Cauchys integral formula.
Would anyone like to give me a hint?
Answer: $\newcommand{\d}{\,\mathrm{d}}$I assume that you haven't learnt the residue theorem yet, and that you mean to use the Cauchy's integral formula:

$$\int_{\gamma}\frac{f(z)}{z-w}\d z=f(w)$$Where $\gamma$ is some suitable closed contour and $f$ is a holomorphic function on $\gamma$'s interior.

Note: $$\frac{e^z}{z(z-3)}=\frac{e^z}{3}\left[\frac{1}{z-3}-\frac{1}{z}\right]$$So, assuming $C(0,4)$ is the boundary of the disk centred at $0$, of radius $4$, you can integrate as follows: $$\int_{C(0,4)}\frac{e^z}{z(z-3)}\d z=\frac{1}{3}\int_{C(0,4)}\frac{e^z}{z}\d z-\frac{1}{3}\int_{C(0,4)}\frac{e^z}{z-3}\d z$$And apply Cauchy's formula individually on the two integrals.
Comment: This makes sense, thanks alot!
Answer: @FShrike's answer using partial fraction decomposition is good.
Another option is to deform the path.  Make a new path which goes around a small circle at $0$ starting on the real axis, then moves along the real axis to $3$, then moves around a small circle at $3$, then returns to the starting point.
The integral around $C(0,4)$ is the same as the integral along this new path since they are homotopic in the domain.  However the "forwards" and "backwards" portions of the integration along the real axis cancel.  So you can split this integral into the sum of the integral around each circle individually.  You can then apply Cauchy's theorem to both of these integrals directly, without using partial fraction decomposition.
Comment: The higher level perspective is that both $C(0,4)$ and $C(0,0.1) + C(3,0.1)$ both represent the same homology class in $\mathbb{C} - \{0,3\}$.  So the integral of a closed form around $C(0,4)$ will be equal to the integral of a closed form over $C(0,0.1) + C(3,0.1)$.  $f(z)\textrm{d}z$ is closed if $f$ is holomorphic.


Pandas not reading or writing to CSV

Question: Written below is the question I asked yesterday.
Reading multiple CSV files and joining them horizontally
The code I wrote worked perfectly fine yesterday and I was able to get the combined csv files, but when I want to do it to other folder, by changing path name and file name, the variables and dataframes are not gettings initialised. Here is the code I have written
import pandas as pd
import numpy as np
from pandas.io.common import EmptyDataError

path = '~/Documents/EditedElectoral/Torpa_Full_Data/'

def merged_data(i):
    try:
        age = pd.read_csv(path+str(i)+'_trimmed.pdf-age.csv', header=None, error_bad_lines=False, delim_whitespace=True)
    except EmptyDataError:
        age = pd.DataFrame()
    try:
        gender = pd.read_csv(path+str(i)+'_trimmed.pdf-gender.csv', header=None, error_bad_lines=False, delim_whitespace=True)
    except EmptyDataError:
        gender = pd.DataFrame()
    try:
        rel = pd.read_csv(path+str(i)+'_trimmed.pdf-rel.csv', header=None, error_bad_lines=False, delim_whitespace=True)
    except EmptyDataError:
        rel = pd.DataFrame()

    combined = pd.concat([age, gender, rel], axis=1)
    combined['block'] = str(i)
    combined.to_csv(path+str(i)+'-combined.csv', header=None, index=None)

for num in range(1,242):

    merged_data(num)

The first error was that csv was not getting exported. When I tried running combined.info() and age.info() I got NameError: name 'combined' is not defined
The file is running properly without any errors, but I am not getting the output. Does it mean that I am committing a logical error? What mistake am I doing in this?
Answer: The problem is the extension, I just tried reading a csv file with your extension and it fails, you need to have just one dot and end with csv.
No idea how it worked before, but it's not the right way
Comment: Hi, Carlos, but the extension was the same in other folders also and it worked perfectly fine last time.
Comment: Try just using the .csv file. If it works at least you know the cause. If it doesn't I will try to think of something else

Pandas not reading or writing to CSV


Find the roots of $x = \tanh(\beta x + \beta h)$

Question: I encountered the equation $x = \tanh(\beta x + \beta h),$ whereby $\beta, h$ are constants. We look for the set of roots for small and large values of the parameter $\beta.$ The problem I have is the fact that $x$ is both in the argument as well as the function itself. The book says that for small values of $\beta,$ the equation has a unique root, while for large values of $\beta$ one gets multiple roots or zeros. I do not see how these conclusions on the number of roots are made. We know that $\tanh$ takes its roots for an argument that vanishes. In this case it means, $\beta x + \beta h = 0.$ Since $\beta$ is assumed to be either small or large, we assume $\beta \neq 0.$ It follows that $x = -h.$ But since in general $h\neq 0,$ this leads to a contradiction, $0 = x = -h.$ Can somebody tell how many roots does the equation above have depending on the parameter $\beta$ ? Thanks.
Answer: Case $0<\beta<1$: we can see $x=\tanh(\beta x+\beta h)$ as a fixed point problem $x=g_\beta(x)$ with $g_\beta$ infinitely many times differentiable. We have that
$$\vert g_\beta'(x)\vert=\beta\vert \operatorname {sech}^2(\beta x+\beta h)\vert\leq \beta<1,\ x\in\mathbb{R}.$$
Then, $x=\tanh(\beta x+\beta h)$ has a unique solution for $\beta<1$.
Case $\beta\gg1$: the number of zeroes also depends on h. Graphically, $\tanh(\beta x+\beta h)$ comes from translating $\tanh x$ horizontally $\vert h\vert$ units to the right if $h<0$ or to the left if $h>0$, and then compressing the graph of $\tanh (x+h)$ horizontally by a factor of $\beta$. For instance:
$\beta=20,h=-1,\text{ with desmos }$" />
Then, graphically, we should see one or more intercepts, depending on $\beta$ and $h$. To prove that there is at least one intercept we can work with the fixed problem $x=\tanh(\beta x+\beta h)=g_\beta(x)$ again, but this time we choose an interval for $x$ on which
$$\vert g_\beta'(x)\vert=\beta\vert \operatorname {sech}^2(\beta x+\beta h)\vert<1$$
to apply the fixed point Theorem on that interval. It is possible to find such interval because
$$\lim_{\vert x\vert\to\infty}\operatorname {sech}(x)=0.$$
Comment: It's $\tanh$ in all the above. I just changed it. I think that's how it was written before somebody else edited it.
Comment: Do you mean by $\tan$ rather the tangent hyperbolicus, $\tanh$ ?
Comment: Thanks. I do not see though, how for large $\beta$ there could me more than one intercept, the fixed point problem providing a unique solution. I though first that $\tanh$ is periodical, but this is false. Can you elaborate little bit in your argument to show that for large $\beta$ there can be more than one root of the equation ?
Comment: I can among different values for $h$ and $\beta,$ find at most 2 roots for $h=0.$
Comment: Hi @user996159. Sure! In the case $\beta$ is large we have a unique solution on an interval on which $\vert\operatorname{sech}(\beta x+\beta h)\vert\ll1 $. This uniqueness does not necessarily imply uniqueness on the whole real line. Finally, for instance, when $h=0$ and $\beta=100$ there are three intercepts: $(-1,-1)$, $(0,0)$ and $(1,1)$.


Como resolvo isto: Field error in object 'fatura' on field 'demandaPontaKW': rejected value [kWh: 1.582,05];

Question: Bom dia pessoal, estou com uma dúvida referente a persistência de dados utilizando máscara do maskMoney, na minha classe os atributos estão como double e na minha view quando utilizo a máscara é enviado uma string, como posso resolver isso de uma forma que não precise parar de usar a máscara e os dados consigam ser persistidos normalmente? Abaixo segue minha view, Classe e o jquery.
HTML:
     <form th:action="cadastrar" method="post" th:object="${fatura}">

   Demanda Ponta:
 <input type="text"  class="form-control" id="demandaPonta" autocomplete="off" th:field="*{demandaPontaKW}" placeholder="kWh: 0,00">

   Demanda Fora Ponta:
   <input type="text"  class="form-control" id="demandaForaPonta" autocomplete="off" th:field="*{demandaForaPontaKW}" placeholder="kWh: 0,00">

Jquery:
 $('#demandaPonta').maskMoney({
      prefix: 'kWh: ',
      allowNegative: false,
      thousands: '.', decimal: ',',
      affixesStay: true
                    });

      $('#demandaForaPonta').maskMoney({
       prefix: 'kWh: ',
       allowNegative: false,
       thousands: '.', decimal: ',',
       affixesStay: true
                    });

Classe:
@Entity

public class Fatura {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "demanda_ponta_kw")
private Double demandaPontaKW;

@Column(name = "demanda_fora_ponta_kw")
private Double demandaForaPontaKW;

}
Obs: apenas frizando que os métodos de acesso e HashCode and Equals estão criados normal na classe coloquei a parte do código que realmente importa.
Answer: Como na sua entidade você utiliza o tipo Double para demandaPontaKW logo o spring vai rejeitar o tipo string "kWh: 1.582,05" com a mensagem de erro informada.
Na sua classe controller ou service da sua aplicação você precisa primeiro converter de String para Double, retirando "kWh: " e alterando a formatação numérica para o padrão, para isso use a lógica abaixo:
String consumoPonta = "kWh: 1.582,05";
String valor_consumoPonta = consumoPonta.substring(5).replace(".", "").replace(",", ".");
double valorDouble_consumoPonta = Double.parseDouble(valor_consumoPonta);
System.out.println(String.format("%.2f", Double.valueOf(valorDouble_consumoPonta)));


Proving $|f'(z)|\leq\frac{\text{Re}(f(z))}{\text{Re}(z)}$

Question: Studying for a preliminary exam, I came across the following question:

Let $D = \{z \in \Bbb C : \text{Re}( z )> 0\}$ and $f : D \to D $ be a holomorphic function. Prove that $$|f'(z)|\leq\frac{\text{Re}(f(z))}{\text{Re}(z)}\quad \text{for all }z\in D.$$

I thought the best way might be to use the fact that harmonic functions satisfy the maximum modulus principle, too, along with the limit definition of the derivative, but I wasn't able to get it worked out. How should I approach this problem?
Comment: This is a part of Schwarz-Pick theorem (the half-plane case); see e.g. Wikipedia (there you'll find a proof and some context)
Comment: The outline of a possible proof can be found here: http://anhngq.wordpress.com/2009/12/17/schwarzs-lemma-schwarz-pick-theorem-and-some-applications-involving-inequalities/ ,too.
Answer: Let's put this into wider context.
Fact 1. If $D$ is a simply connected domain and  $f:D\to D$ is a holomorphic map with fixed point $a$, then   $|f'(a)|\le 1$.
Proof: apply the Schwarz lemma to $g^{-1}\circ f\circ g$ where $g$ maps the unit disk onto $D$ so that $g(0)=a$. $\quad \Box$
Remark: one can drop "simply connected" in Fact 1, but then the proof requires more    tools.
To apply Fact 1 here, fix $a\in D$ and consider
 $g=\phi\circ f$ where $\phi$ is an automorphism $\phi$ of $D$ that sends $f(a)$ back to $a$. Since $|g'(a)|\le 1$, it follows that $|f'(a)|\le |\phi'(f(a))|^{-1}$.
Notice that $D$ can still be any simply connected domain above. Its shape comes into play only when we construct  $\phi$. Which for the right half-plane turns out to be
$$\phi(z)=\frac{\operatorname{Re}a}{\operatorname{Re}f(a)}\, (z-\operatorname{Im}f(a)) +i   \operatorname{Im}a $$
Comment: For an even wider context, see http://math.stackexchange.com/a/320169/


Python Applying a CDF after Fitter

Question: I would like to apply the best fit CDF found by Fitter to each value in a number of panda data-frame columns by hopefully passing the Fitter results to Scipy Stats (or another library?).
I can get the distribution function easily enough from Fitter with the following code:
import numpy as np
import pandas as pd
import seaborn as sns
from fitter import Fitter
from fitter import get_common_distributions

from fitter import get_distributions

dataset = pd.read_csv("econ.csv")
dataset.head()

sns.set_style('white')
sns.set_context("paper", font_scale = 2)

sns.displot(data = dataset, x = "Value_1",kind = "hist", bins = 100, aspect = 1.5)

spac = dataset['Value_1'].values
f = Fitter(spac, distributions=get_distributions())

f.fit()
f.summary()

f.get_best(method='sumsquare_error')

This provides me with an output for Value_1:
{'norminvgauss': {'a': 1.87,
'b': -0.65,
'loc': 0.46,
'scale': 1.24}}
Now this is where I am stuck:
Is there a way to pass this information back to Scipy Stats (or another library) so I can calculate the cumulative distribution function (CDF) of the best fit for each value in each column?
The dataset columns range from Value_1 to Value_99 with about 400 rows - Once I know how to feed the fitter results back into scipy stats I should be able to write a simple for loop to apply this over each column.
An example of the result would be like:

ID
Value1
CDF_BestFit_Value1

n
0.9
0.33

n+1
0.7
0.07

Much appreciated in advanced for anyone who is able to help with this.
Comment: Did you find an answer to this? @MikalFischer
Answer:
Is there a way to pass this information back to Scipy Stats (or another library) so I can calculate the cumulative distribution function (CDF) of the best fit for each value in each column?

IIUC, the information you are trying to pass back to scipy.stats is like
{'norminvgauss': {'a': 1.87, 'b': -0.65, 'loc': 0.46, 'scale': 1.24}}

In this example, you would want to evaluate the CDF of the norminvgauss distribution with these parameters. The difficulty is that you want to do this programatically given the name of the distribution family as a string and the parameter name/value pairs as a dictionary.
One way to extract the name of the distribution family and the parameter info is like:
dist_name, params = list(d.items())[0]

(Perhaps there are more elegant ways, but this is the first that comes to mind. It's unusual to have just single key in the dictionary, but I often iterate over dictionaries like for dist_name, params in d.items().)
Then, the way to get the distribution family object is:
dist_family = getattr(stats, dist_name)

I would pass the parameters to the distribution family object to create a "frozen" distribution with those parameters:
dist = dist_family(**params)

and then you can evaluate its cdf at whatever arguments you please.
dist.cdf([0, 0.5, 1])

For easier copy-pasting:
from scipy import stats
d = {'norminvgauss': {'a': 1.87, 'b': -0.65, 'loc': 0.46, 'scale': 1.24}}

dist_name, params = list(d.items())[0]
dist_family = getattr(stats, dist_name)
dist = dist_family(**params)
dist.cdf([0, 0.5, 1])
# array([0.45497638, 0.69433145, 0.87312848])

The rest - extracting the arguments from the dataframe and writing the results to the dataframe - is just pandas, and it sounds like you have that under control.

Python Applying a CDF after Fitter


SQL, Range between

Question: I have this:
 SELECT

 firstname, lastname, Sexe, Weight,
 sum(E.Weight) OVER (ORDER BY E.Height
                     RANGE BETWEEN 10 PRECEDING AND 5 FOLLOWING ) AS SumHeight

 FROM HR.Employees AS E
 ORDER BY E.Height

But I get this error:

RANGE is only supported with UNBOUNDED and CURRENT ROW window frame delimiters.
Comment: Isn't range between and (< >) same?
Comment: You mean like this: SELECT firstname, lastname, Sexe, Weight,
 sum(E.Weight) OVER (ORDER BY E.Height <> BETWEEN 10 PRECEDING AND 5 FOLLOWING ) AS SumHeight

 FROM HR.Employees AS E
 ORDER BY E.Height      that doesnt work
Answer: Pretty much what it says - you've got to have either unbounded or current row at the ends of a range.
You can't do what you're trying to do.
Answer: This link (T-SQL OVER Clause) shows that:

<unsigned value specification> PRECEDING:
      Specified with <unsigned value specification> to indicate the number of rows or values to precede the current row. This
  specification is not allowed for RANGE.

So your <window frame preceding> and <window frame following> in the RANGE specification can only use UNBOUNDED PRECEDING|CURRENT ROW, respectively UNBOUNDED FOLLOWING|CURRENT ROW.
You are probably looking for ROWS i/o RANGE?
Comment: Ok, but what is the alternative in SQL2012?
Comment: @savantKing use `ROWS BETWEEN ... AND ...`
Answer: You should have use ROWS instead of RANGE:
SELECT
 firstname, lastname, Sexe, Weight,
 SUM(E.Weight) OVER (ORDER BY E.Height
                 ROWS BETWEEN 10 PRECEDING AND 5 FOLLOWING ) AS SumHeight
 FROM HR.Employees AS E
 ORDER BY E.Height

Otherwise if you have to use RANGE then you have to what it suggest i.e. use UNBOUNDED and/or CURRENT_ROW delimiters:
SELECT
 firstname, lastname, Sexe, Weight,
 SUM(E.Weight) OVER (ORDER BY E.Height
                 RANGE UNBOUNDED PRECEDING) AS SumHeight
 FROM HR.Employees AS E
 ORDER BY E.Height

The above of course does not meet what you need but just showing you the possible way to use it.

SQL, Range between


What is difference between `loadChildren: () => import('./hoge.module.ts).then(m => m.HogeModule)' and loadChildren: './hoge.module#HogeModule'?

Question: Issue
We get an error cannot find module in case following structure.

app-routing.module.ts

const routes: Routes = [
  {
    path: CHILD_MANAGEMENT_PORTAL.baseUrl,
    canActivate: [AuthGuard],
    component: EnvelopeComponent,
    loadChildren: () =>
      import('./features/child-management/child-management.module').then(
        m => m.ChildManagementModule
      ),
    data: {
      menuResolver: ChildManagementMenuResolver,
      pageTitleResolver: ChildManagementPageTitleResolver,
      portalData: CHILD_MANAGEMENT_PORTAL
    }
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

child-management-routing.module.ts : wrong

const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: './dashboard/child-dashboard.module#ChildDashboardModule'
  },
  {
    path: '**',
    redirectTo: 'dashboard'
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  declarations: []
})
export class SalesArrangementManagementRoutingModule {}

We could solve this error by only changing loadChildren of child routing.module from loadChildren: './hoge.module#HogeModule' to loadChildren: () => import('./hoge.module.ts).then(m => m.HogeModule)'.

child-management-routing.module.ts : correct

const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: () => import('./dashboard/child-dashboard.module').then(m => m.ChildDashboardModule)
  },
  {
    path: '**',
    redirectTo: 'dashboard'
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  declarations: []
})
export class SalesArrangementManagementRoutingModule {}

But I could not understand why. (I did not change app-routing.module.ts...)
So could you explain the difference?
Comment: If you think my answer is correct or other any answer do mark it as correct answer as it helps others who comes to this question to find right answer. Thank you.
Answer: It seems like you upgraded from Angular 7.x to 8.x and this is where the scheme changed.
Explanation (From angular docs)

When Angular first introduced lazy routes, there wasn't browser support for dynamically loading additional JavaScript. Angular created our own scheme using the syntax loadChildren: './lazy/lazy.module#LazyModule' and built tooling to support it. Now that ECMAScript dynamic import is supported in many browsers, Angular is moving toward this new syntax.
In version 8, the string syntax for the loadChildren route specification was deprecated, in favor of new syntax that uses import() syntax.
Before
const routes: Routes = [{
  path: 'lazy',
  // The following string syntax for loadChildren is deprecated
  loadChildren: './lazy/lazy.module#LazyModule'
}];

After
const routes: Routes = [{
  path: 'lazy',
  // The new import() syntax
   loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
}];

Hope this helps you out.
Answer: This is feature is updated from previous version so if it need to work in your application slight changes to be made
here is a example have a look
error ts1323: dynamic import is only supported when '--module' flag is 'commonjs' or 'esnext
I got the first error when i tried using static lazy loading import
loadChildren: './lazy/lazy.module#LazyModule

i decided to use dynamic import
loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)

This threw the second error.
I then fixed it by simply adding "module": "esNext" to compilerOptions in tsconfig.json file and updated "module": "es2015" to "module": "esNext" in both tsconfig.app.json and tsconfig.tns.json files.
That solve the problem for me


Problema ao apagar um campo da tabela

Question: Quando tento apagar uma linha da minha tabela, ele me retorna esse erro
ERROR:  update or delete on table "menu" violates foreign key constraint "fk_menu_id" on table "view_menu"
DETAIL:  Key (menu_id)=(2370) is still referenced from table "view_menu".
O que seria?
Answer: O erro está dizendo que a linha em questão possui informações vinculadas na tabela view_menu, apague primeiro o que está vinculado na tabela view_menu para que possa apagar da tabela menu

Problema ao apagar um campo da tabela


Determining which methods to use to find how close a day is from the average pattern

Question: Would anyone have advice on how to determine how close a day is to matching the average pattern of all days? I would like to take each day of the year and evaluate how close that day is from the average of all days in the year.
Ultimate goal is to select 7 days in the year that are closest to this average pattern.
I think I should be looking for which day has the lowest error, but am not positive.
In this sample image, the red is the average of the year and the blue represents one day. X axis is hours, y is observation.
Answer: Well if I understand correctly, you are just looking for days that closely exhibit the same movements as the average of all days. This can be accomplished by using Dynamic Time Warping. DTW returns the distance between any two series by mapping them. Check it out:
https://www.aaai.org/Papers/Workshops/1994/WS-94-03/WS94-03-031.pdf
Answer: You have evidently have hourly measurements, so you can devise your measure of misfit, say
$$\sum_{h=0}^{23} | y_{ih} - \bar y_h|,$$
or even
$$\sum_{h=0}^{23} (y_{ih} - \bar y_h)^2,$$
and choose days with values closest to 0. Here $y_{ih}$ is the value for $y$ for day $i$ and hour $h$ and $\bar y_h$ is the average over days for hour $h$. I have little interest in advocating either measure  as especially good and still less in attacking others. The point is that you need your own criterion for "close to average" that matches your concerns, and then it's just computing.
This criterion does not explicitly focus on matching times of peaks or troughs. As just one more variation, it could be that misfit is better measured on some transformed scale, e.g. root or logarithm.
Comment: +1 because this is the first answer to address the underlying problem: first one has to specify what "close" might mean with sufficient clarity to permit one to construct a quantitative measure of closeness.  The rest is a matter of applying computer science principles to devise an acceptably efficient algorithm to select the closest day.
Answer: IDontKnowCode's answer is good, you can definitely use DTW to compare the sets of two signals and return a distance, the lowest 7 values would be the ones that match the best. It would also be interesting to compare the cross-correlation. I expect you would have the same 7 return with the highest correlation (cross-corelation of 1 means perfectly matching, DTW distance of 0 means perfectly matching), but both use different techniques.
Comment: Not so. 2 3 4 and 4 6 8 have a correlation of 1, but they do not match. Correlation measures linearity, not agreement, and the correlation being cross doesn't change that.
Comment: @NickCox, very good point. The example you give would give a distance of zero in DTW if the signals are normalised to one another. If they're not normalised then I wonder if the seven pairs with the lowest DTW distance would be the same seven with the highest correlation. I also wonder if that would be the same if the signals are not normalised for DTW. I should note I always normalise when doing cross-correlation so that the value is between -1 and 1.
Comment: Normalise means different things in different places, but I pick up no sense from the question that the OP wants any of them. Engineers sometimes do different things, but in statistical literature I know it's the rule that correlations are scaled to have absolute value no greater than 1.


Classification model to predict continuous classes

Question: Is it possible to create a classification model which can predict continuous classes, like a number?
So far I've working with predictor which can predict one of two classes. I've searched about it and I just found references about continuous features.
I have a bunch of features (numbers) to predict a variable, namely 12 features, and  observations labelled (with the variable to predict) that can be considered train data.
Comment: Yes which? Continuous dependent variable? I think you need to elaborate on your problem, because if the predicted value is continuous, you can apply anything from simple linear regression to random forests and PLS. Describe your problem in detail, please.
Comment: What do you mean by "continuous classes"? Ordinal variables? Or just a continuous dependent variable?
Comment: @January yes, like predicting a number.
Answer: If the dependent variable is metric (continuous, and 1 means twice as much as 0.5), the model is called a regression model, not a classification model.
There are also models like logistic regression that are in between classification and regression: it is a classifier in that the classes are distinct groups, but model actually models the class membership probability which is metric and that's why it is logistic regression.
If the dependent variable still comes in groups, but they do have an order ("2" is larger than "1", but not necessarily twice as much), this is called ordinal regression.
If your problem has proper groups, but you encounter mixtures of the classes, that is yet another situation (regression again, but what kind depends on the actual situation/problem at hand).
I agree with @January that we need more information what your data is about to give you more detailed and sensible answers.


Angular 2 Custom Theme , SCSS error

Question: I am new to Angular 2, and brand new to SCSS (I have always used css). I am trying to setup a custom theme for my angular-cli project that goes along with our branding colors.
I found a stackoverflow question (Angular2 Material - Real custom theming?) that I thought would work, but sadly I am getting a error that looks like a problem with Angular 2 parsing my .scss custom theme file. I have made the necessary addition of my .scss file in the angular-cli.json located in the root of the application, and placed the new .scss file in the src folder alongside the style.css originally created by angular-cli project setup. Below is the .scss file I created.
@import '~@angular/material/core/theming/all-theme';

@include md-core();

$ae-brand-indigo: (
    50: #e0ebf3,
    100: #b3cee1,
    200: #80adce,
    300: #4d8cba,
    400: #2673ab,
    500: #005a9c,
    600: #005294,
    700: #00488a,
    800: #003f80,
    A200: #6a9bff,
    A400: #3778ff,
    A700: #1e67ff,
    contrast: (
        50: $black-87-opacity,
        100: $black-87-opacity,
        200: $black-87-opacity,
        300: $black-87-opacity,
        500: white,
        600: white,
        700: white,
        800: white,
        900: white,
        A100: $black-87-opacity,
        A200: $black-87-opacity,
        A400: $black-87-opacity,
        A700: white,
    )
 );

$ae-brand-orange: (
    50: #fef3e4,
    100: #fde0bb,
    200: #fccc8e,
    300: #fab861,
    400: #f9a83f,
    500: #f8991d,
    600: #f7911a,
    700: #f68615,
    800: #f57c11,
    900: #f36b0a,
    A100: #ffffff,
    A200: #fff1e9,
    A400: #ffd1b6,
    A700: #ffc19c,
    contrast: (
        50: $black-87-opacity,
        100: $black-87-opacity,
        200: $black-87-opacity,
        300: $black-87-opacity,
        400: $black-87-opacity,
        500: white,
        600: white,
        700: white,
        800: white,
        900: white,
        A100: $black-87-opacity,
        A200: $black-87-opacity,
        A400: $black-87-opacity,
        A700: white,
   )
 );

// mandatory stuff for theming
$ae-primary: md-palette(ae-brand-indigo);
$ae-accent:  md-palette($ae-brand-orange);
$ae-warn: md-palette($md-red);

// include the custom theme components into a theme object
$ae-main-theme: md-light-theme($ae-primary, $ae-accent, $ae-warn);

// include the custom theme object into the angular material theme
@include angular-material-theme($ae-main-theme);

I get the following error stacktrace when building and starting up my dev server.

ERROR in
  ./~/css-loader!./~/postcss-loader!./~/sass-loader!./src/ae-main-
  theme.scss Module build failed: undefined
          ^   Argument $map of map-get($map, $key) must be a map
Backtrace:
      node_modules/@angular/material/core/theming/_theming.scss:19, in
      function map-get
      node_modules/@angular/material/core/theming/_theming.scss:19, in
      function md-palette
      stdin:76
      in C:\Users\jstafford\Desktop\working\ae-
      ui\node_modules\@angular\material\core\theming_theming.scss (line 19,
      column 14)
      @ ./src/ae-main-theme.scss 4:14-166
      @ multi styles
ERROR in ./src/ae-main-theme.scss)` must be a map

Now, I know I am defining a custom palette here. The only examples I have seen on the material 2 getting started page use $md-red, $md-indigo and the different hues of that color that are predefined. Can anyone help me to get this working so I can truly customize like I saw here.  What am I missing?
Comment: being new to scss, I left the import 'variables' out because I thought it was something that was unique to the scss setup of the person who originally posed this in the stackoverflow question I referenced. Not sure if this is related to my problem.
Answer: I forgot a $ sign on my indigo variable (this is what caused the parser exception):
$ae-primary-palette: md-palette($ae-brand-indigo);
/* -----------------------------^ */

I also added my choice of primary and secondary colors:
$primary-color: map-get($ae-primary-palette, 500);
$secondary-color: map-get($ae-accent-palette, 500);

Angular 2 Custom Theme , SCSS error


Query em coluna tipo date com filtro da semana atual

Question: Andei procurando um comando em mysql, que fizesse tal função. A finalidade disso é que tenho que exibir um programação de itens da semana atual. De domingo a sábado. Existe um query que faça esse filtro ? Bem a coluna é do tipo date, Y-m-d.
Comment: Você já tentou usar a função WEEK()? Se liga nesse https://stackoverflow.com/questions/6710342/mysql-grouping-by-week
Comment: Sim, mas ela não me retorna nenhum registro
Answer: Use a função YEARWEEK em conjunto com a CURDATE:
SELECT *
  FROM tabela
 WHERE YEAR(data) = YEAR(CURDATE())
   AND YEARWEEK(data, 1) = YEARWEEK(CURDATE(), 1)

YEAR
Returns the year for date, in the range 1000 to 9999, or 0 for the "zero" date.

Em tradução livre:

Retorna o ano de uma data, em um intervalo de 1000 até 9999, ou 0 para a data "zero".

YEARWEEK
Returns year and week for a date.

Em tradução livre:

Retorna o ano e semana de uma data.

CURDATE
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.

Em tradução livre:

Retorna a data atual como o valor no formato 'YYYY-MM-DD' ou YYYYMMDD, dependendo do contexto em que a função é utilizada (string ou numérico).