Flutter does not work anymore after upgrading

Question: My project was working perfectly and Just today i have upgrade my Flutter then everything start going run.
At the bottom is the error they give me.
Please help me.
file:///Users/macbook/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/animated_background-1.0.4/lib/image_helper.dart:17:30: Error: The argument type 'dynamic Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.
 - 'ImageInfo' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/macbook/Documents/flutter/packages/flutter/lib/src/painting/image_stream.dart').
 - 'ImageStreamListener' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/macbook/Documents/flutter/packages/flutter/lib/src/painting/image_stream.dart').
Try changing the type of the parameter, or casting the argument to 'ImageStreamListener'.
    newStream.removeListener(listener);
                             ^
file:///Users/macbook/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/animated_background-1.0.4/lib/image_helper.dart:20:25: Error: The argument type 'dynamic Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.
 - 'ImageInfo' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/macbook/Documents/flutter/packages/flutter/lib/src/painting/image_stream.dart').
 - 'ImageStreamListener' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/macbook/Documents/flutter/packages/flutter/lib/src/painting/image_stream.dart').
Try changing the type of the parameter, or casting the argument to 'ImageStreamListener'.
  newStream.addListener(listener);
                        ^
file:///Users/macbook/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/animated_background-1.0.4/lib/image_helper.dart:21:41: Error: The argument type 'dynamic Function(ImageInfo, bool)' can't be assigned to the parameter type 'ImageStreamListener'.
 - 'ImageInfo' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/macbook/Documents/flutter/packages/flutter/lib/src/painting/image_stream.dart').
 - 'ImageStreamListener' is from 'package:flutter/src/painting/image_stream.dart' ('file:///Users/macbook/Documents/flutter/packages/flutter/lib/src/painting/image_stream.dart').
Try changing the type of the parameter, or casting the argument to 'ImageStreamListener'.
  return () => newStream.removeListener(listener);
                                        ^
Compiler failed on /Users/macbook/AndroidStudioProjects/alimmentation/lib/main.dart
Finished with error: Gradle task assembleDebug failed with exit code 1

Comment: Have you tried flutter clean? Maybe that'll work? Also perhaps post the output of flutter doctor and flutter run -v.... Also make sure you have the latest flutter SDK  and check out this thread just came across it https://github.com/flutter/flutter/issues/24645
Comment: Why do you not just fix the code? It clearly says what the problem is and upgrading the framework can introduce breaking changes.
Comment: Here is my flutter doctor

`flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v1.6.3, on Mac OS X 10.14.4 18E226, locale fr-BF)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] iOS toolchain - develop for iOS devices (Xcode 10.2)
[✓] Android Studio (version 3.4)
[✓] VS Code (version 1.34.0)
[✓] Connected device (1 available)

• No issues found!`
Comment: Perhaps post it in the question next time but good to know there are no issues
Comment: @JoeA Thanks For sure new time I'll do it. Is there any solution?
Comment: The only solution I can think is as I mentioned: (1) Make sure you have the latest flutter sdk, (2) try flutter clean  or (3) It could be an AndroidX compatibility issue found here https://flutter.dev/docs/development/packages-and-plugins/androidx-compatibility, (4) update the code I would recommend that
Comment: im pretty sure the error is saying that the parameter list of the `listener` function is wrong. the parameters need to match that of the typedef `ImageStreamListener`
Comment: see https://groups.google.com/forum/#!topic/flutter-announce/NWTszrEq9U0 - it was done in [v1.6.2](https://github.com/flutter/flutter/wiki/Changelog#v162)
Comment: Try upgrading the photo_view package in pubspec.yaml to latest version, it solved my problem.
Answer: Solved a similar issue by replacing
/*...*/.addListener((ImageInfo image, bool synchronousCall) { /*...*/ });

with
import 'package:flutter/painting.dart';

/*...*/.addListener(new ImageStreamListener((ImageInfo image, bool synchronousCall) { /*...*/ }) as ImageStreamListener);

Answer: I had the same problem, here is some code only as an example
Code that broke:
var sunImage = new NetworkImage(incident.mobileSignature[0].uriFile,
          headers: AuthenticationService.getAuthHeaders());
sunImage.obtainKey(new ImageConfiguration()).then((val) {
    var load = sunImage.load(val);
    load.addListener((listener, err) async {
        ByteData data = await listener.image.toByteData(format:ui.ImageByteFormat.png);
        setState(() => this.signatureImage = data);
    });
  });
}

The code broke on line load.addListener((listener, err) async { ....
I solved creating an ImageListener function that does the same as my previous function with the listener variable. And then create an ImageStreamListener that receives this ImageListener as parameter. Note also that you can send as parameters onError and onChunk to the ImageStreamListener.
var sunImage = new NetworkImage(incident.mobileSignature[0].uriFile,
          headers: AuthenticationService.getAuthHeaders());
sunImage.obtainKey(new ImageConfiguration()).then((val) {
    var load = sunImage.load(val);
    ImageListener imageListener = (ImageInfo imageInfo, syncCall) async {
        ByteData data =
              await imageInfo.image.toByteData(format: ui.ImageByteFormat.png);
          setState(() => this.signatureImage = data);
    };
    ImageStreamListener listenerStream = new ImageStreamListener(imageListener);
    load.addListener(listenerStream, onError: ...., onChunk: ......); // These last parameters are optional
});

Answer: Change your animated_background dependency in the pubspec.yaml file to the following:
animated_background:
    git: https://github.com/AndreBaltazar8/flutter_animated_background.git

Do a flutter clean afterwards and rebuild.
Reason: That happens because that dependency has actually been changed in the repo to match some of the framework changes related to the Image API, but not in the pub.dev.
Answer: Facing ImageStreamListener error in flutter printing plugin. I am using flutter 1.5.4 hotfix 2 version.
Use printing: 2.0.2  # fix it at this version to solve ImageStreamListener issue.
Hope it helps


commutativity between the lift of a Galois group and the Galois group of the cyclotomic $\mathbb{Z}_p$-extension

Question: Let $K/\mathbb{Q}$ be a Galois number field and let $K_{\infty}/K$ be its cyclotomic $\mathbb{Z}_p$-extension defined by $K_{\infty}=K\cdot \mathbb{Q}_{\infty}$, where $\mathbb{Q}_{\infty}$ is the unique (cyclotomic) $\mathbb{Z}_p$-extension of $\mathbb{Q}$.
Let $\tau \in \text{Gal}(K_{\infty}/K)$ be a topological generator for $\text{Gal}(K_{\infty}/K)$ and for each $g \in \text{Gal}(K/\mathbb{Q})$, we fix a lift $\tilde{g} \in \text{Gal}(K_{\infty}/\mathbb{Q})$ of $g$.
I would like to know under which conditions one has that $\tilde{g}\tau=\tau\tilde{g}$, for all $g \in \text{Gal}(K/\mathbb{Q})$. This seems to be true if one assumes that $K\cap \mathbb{Q}_{\infty}=\mathbb{Q}$, but is it possible to find a necessary and sufficient condition?
Comment: What do you mean by "cyclotomic $\Bbb Z_p$ extension?
Comment: If $\zeta_{p^{n+1}}$ is a primitive $p^{n+1}$-th root of unity, then $\mathbb{Q}(\zeta_{p^{n+1}})$ has a unique subfield $\mathbb{Q}_n$ of order $p^n$ over $\mathbb{Q}$. Then $\mathbb{Q}_{\infty}$ is defined as the union of all such $\mathbb{Q}_n$.
Answer: I'm not sure there's much one can say in general. The condition that $\Bbb Q_\infty$ and $K$ be linearly disjoint over $\Bbb Q$ gives a direct product representation which of course implies the commutator relation you want. However, if we take the fully general approach, we see

$$\text{Gal}(K_\infty/K)=\text{Gal}(\Bbb Q_\infty K/K)\cong\text{Gal}(\Bbb Q_\infty/\Bbb Q_\infty\cap K)$$

This of course is how we know $\text{Gal}(K_\infty / K)$ is isomorphic to a subgroup of $\widehat{\Bbb Z}$. But the usual s.e.s. is

$$1\to \text{Gal}(K_\infty/K)\to\text{Gal}(K_\infty/\Bbb Q)\to\text{Gal}(K/\Bbb Q)\to 1$$

and a lift of $g\in \text{Gal}(K/\Bbb Q)$ is just any element of $\stackrel{\sim}{g}\text{Gal}(K_\infty/K)$. And the condition any such element commutes with your $\tau$ is just that $\text{Gal}(K_\infty/K)\le Z( \text{Gal}(K_\infty/\Bbb Q))$ since all elements of $\text{Gal}(K_\infty/\Bbb Q)$ are in some coset of some $\stackrel{\sim}{g}$. And as such this condition is both necessary and sufficient.
This of course recovers the case you mention, as then

$$\text{Gal}(K_\infty/\Bbb Q)=\text{Gal}(K\Bbb Q_\infty/\Bbb Q)\cong\text{Gal}(K/\Bbb Q)\times \text{Gal}(\Bbb Q_\infty/\Bbb Q_\infty\cap K)$$

and the right factor is abelian.
Comment: Thank you very much for this answer. I am not 100% sure I get the last part where you say "This of course recovers the case you mention". Do you mean that the case $K \cap \mathbb{Q}_{\infty}=\mathbb{Q}$ satisfies $Gal(K_{\infty}/K)\leq Z(Gal(K_{\infty}/\mathbb{Q}))$, or something more, i.e. that the case I mention is also necessary for $Gal(K_{\infty}/K)\leq Z(Gal(K_{\infty}/\mathbb{Q}))$ to hold?
Comment: @JakeHaider yes, I'm talking about the linearly disjoint case. It's not necessary, but if you have the linearly disjoint case it's clear that the given group is contained in the center because of the direct product representation


How to handle communication errors properly? QT SerialPort

Question: I have a bidirectional communication through the serial port.
MyClass::MyClass(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    //setUp

    connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this,
           SLOT(handleError(QSerialPort::SerialPortError)));
}

void MyClass::handleError(QSerialPort::SerialPortError error)
{
  //show error
  //close connection
}

void MyClass::send(QString data)
{
    if(!data.endsWith('\r'))
        data.append('\r');

    //should be like this:
    serial->write(data.toLocal8Bit());
    serial->waitForBytesWritten(TIMEOUT);

    //or this?
    if( serial->write(data.toLocal8Bit()) < 0 )
        emit serial->error(QSerialPort::WriteError);

    if(!serial->waitForBytesWritten(TIMEOUT))
        emit serial->error(QSerialPort::TimeoutError);

}

void MyClass::receive(char &dest, int size)
{
    //similar to send
}

Namely, handleError will automatically handle the Serial Port Errors or should I detect & throw them?
Which of the 2 ways is more correct? Or none of them is correct?
Answer: This:
if (serial->write(data.toLocal8Bit()) < 0 )
    emit serial->error(QSerialPort::WriteError);

is wrong, since the QSerialPort class already emits the signal, why do you want to do it yourself?
You should both handle the error signal that the QSerialPort emits, and handle any immediate errors returned by the write, read and other methods. You need to handle the signal because the reading and writing happens asynchronously. A write that "succeeds" and returns the number of bytes you intended, does simply mean that the device was open and was in a "usable" state at the moment. The actual write happens in the background and may fail at any time.
The simple, and correct thing to do, is to have a state machine that implements the communications protocol you're after. The state machine framework is there to help you.


Equivalent for HAProxy's option forwardfor/close in Pound

Question: I'm switching from HAProxy to Pound and I need to know if there is an equivalent of
option forwardfor
option httpclose

in Pound.
BTW, I'm already using the
HeadRemove "X-Forwarded-For"

in Pound.
Thanks
Answer: Looks like Pound does this by default. From http://www.apsis.ch/pound/

As a general rule, Pound passes all headers as they arrive from the client browser to the back-end server(s). There are two exceptions to this rule: Pound may add information about the SSL client certificate (as described below), and it will add an X-Forwarded-For header. The general format is:

    X-Forwarded-for: client-IP-address

My problem was that the application (OpenStack) wasn't using the X-Forwarded-for header by default. I set
--use_forwarded_for=True
and problem solved.


Who was chosen the best soccer player of the 1958 world cup, Didi or Raymond Kopa?

Question: In this video, tv sports journalist Maldini claims in the 1958 World Cup, Raymond Kopa was chosen the best player of the World Cup over Didi, Pelé, Garrincha and Vavá.
Best 11 soccer players of France (spanish)
And in this article, it's claimed that Didi received the golden ball award of the 1958 world cup, an award which is supposedly given to the best player of the world cup, and which its existence before 1978 is in debate.

A teenage Pele was only denied the Golden Ball at in 1958 by team-mate
Didi

100 World cup heroes
Who was chosen the best soccer player of the 1958 World Cup, Didi or Raymond Kopa?
Answer: Didi was given it.
The Golden Ball award for best player was not officially given (in its current form) until 1982. Awards from before this time may be somewhat disputable, but nevertheless...
FIFA's official website lists Didi as the recipient of the 1958 (and 1962) World Cup Golden Ball awards. One may presume that the organization responsible for the event knows who was awarded what.
The same source lists Raymond Kopa as receiving the "France Football Ballon d'Or - FIFA World Player Gala" as well. This is not the World Cup Golden Ball award. Either Maldini is confused about the names, has used an alternative inaccurate source, or made up the claim themselves.


how to add second image on ImageView

Question: I am a beginner Android developer, so I'm sorry if the answer to this question is obvious.
I want to add two pictures to imageView. The first picture will be bigger and its position won't change. And the second will be smaller and its position will change, vertically (I think there is 16 combinations where it could be located). The position of the second image will change only when the user presses the button. Is there any way to set two pictures into one bitmap and then draw them to ImageView?
Comment: make it li'l more clear.
Comment: I just need to add two images toogether and draw them to ImageView.
Answer: If set two pictures into one bitmap and then draw them to ImageView is an requirement, I would suggest the following:
You can create a canvas from larger bitmap, and draw your smaller bitmap on it, and display the drawn bitmap on Image View.
You have to calculate the position of drawing tough.
Bitmap largeImage; // Get it with your own approach, this refers to larger image
Bitmap smallImage; // Get it with your own approach, this refers to small image
ImageView yourImageView;

Canvas canvas = new Canvas(largeImage);
//0f and 0f refers to coordinates of drawing, you may want to do some calculation here
// since you have like 16 different positions
canvas.drawBitmap(smallImage, 0f, 0f, null);

yourImageView.setImageBitmap(largeImage);

Comment: This is exactly what i was looking for, but it doesn't shows me smallImage on top of it.
Comment: It was my mistake, i fix it, thank you u solved mi problem :)
Answer: An ImageView is related to a single bitmap. You could draw yourself the bitmap and then pass it to the ImageView or you could use other component, like a gridlayout (or gridview) with the static image for background and the dynamic image wherever you want.
Sorry if I did not get your question right...
Comment: Gridview isn't exactly what i was looking for. I just want to make bitmap from two pictures and then draw it to ImageView. But i don't know how... but thanks for your anwser
Comment: You could use canvas for it... Instantiate a Canvas from the static image and draw the other with drawBitmap() on top of it...
Answer: What you should do is following, here's the XML:
<RelativeLayout
android:id="@+id/view_base"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<ImageView
    android:id="@+id/iv_parent"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:src="@drawable/circle" />

<ImageView
    android:id="@+id/iv_child"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

Here's the code with two methods:
//This is what I recommend
RelativeLayout view_base=(RelativeLayout)findViewById(R.id.view_base);

ImageView iv_parent=(imageView)findViewById(R.id.iv_parent);
ImageView iv_child=(imageView)findViewById(R.id.iv_child);

yourButton.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v) {
        iv_child.setBackgroundResource(R.drawable.image);
    }
});

//This is how you want it
RelativeLayout view_base=(RelativeLayout)findViewById(R.id.view_base);

ImageView iv_parent=(imageView)findViewById(R.id.iv_parent);
ImageView iv_child=(imageView)findViewById(R.id.iv_child);

ImageView iv_single=(imageView)findViewById(R.id.iv_single);

yourButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
        iv_child.setBackgroundResource(R.drawable.image);
        iv_single.setImageBitmap(getMergedBitmap());
    }
});

//This method will convert view to bitmap
private Bitmap getMergedBitmap(){
    view_base.setDrawingCacheEnabled(true);
    view_base.buildDrawingCache();
    return view_base.getDrawingCache()
}

Answer: Use FrameLayout with two ImageView. And then set bitmap to that imageviews.

how to add second image on ImageView


'Jupyter' is not recognized as an internal or external command

Question: I installed python and jupyter notebook through the Anaconda distribution. I have been successfully using jupyter notebook for weeks and it has run perfectly fine. However, I can only launch a notebook through the Anaconda Navigator GUI.
When I try to run the command (in command prompt) to start a notebook it says
'jupyter' is not recognized as an internal or external command

This is also the same case with Python
'python' is not recognized as an internal or external command

I am using Windows 10. I am assuming its a PATH issue but I have not had any luck with the solutions I found from other posts. I am relatively new to programming and python so any help would be greatly appreciated.
Comment: Do you have anaconda prompt installed?  Then you can use `python` or `jupyter` there.
Comment: possibly try using [choco package manager](https://chocolatey.org/). I still had issues installing jupyter so I ended up using a Cloud VM ( AWS -> EC2 - use the free tier AMI ). [doco](https://docs.aws.amazon.com/dlami/latest/devguide/setup-jupyter.html). [tutorial](https://www.fast.ai/)
Comment: so both python and jupyter notebook are installed in your conda environments that your command prompt can't locate. If you don't mind you could install them again (not in anaconda), otherwise you need to run them inside anaconda prompt as Kota suggested.
Comment: Probably not in your path. Windows or Unix?
Check your path and see if the jupyter install location is in the path.
Comment: @KotaMori I am trying to run "jupyter" from Anaconda prompt and I get "not recognized" error
Comment: @Confounded Try `conda list` to see if `jupyter` library is installed. If it is not, then `conda install -y jupyter` will install it.  If still `jupyter` is not recognized, then it is most likely the PATH problem.
Answer: Yes, This is the problem which I faced also during the installation of Jupyter Notebook.
But I know the solution of this. I hope, it also works for you as well.

Open cmd.
Type: pip install notebook.
If you Type: **jupyter notebook** - it always shows an error.
So, Type: python -m notebook.

Image shows running Jupyter Notebook
If you feel that this answer is useful and works for you, I expected. So, please press the Up Button for other peoples. So that they can also get some help.
Comment: Did the "pip install notebook" and succeeded and then "python -m notebook"  but got "python.exe: No module named Notebook"
Comment: First, `pip install jupyter notebook` then,
`python -m notebook`
worked for me.
Answer: I've just fixed this issue on my windows 10 machine. My path contained
C:\Users\user\AppData\Local\Programs\Python\Python37\Scripts\

where 'user' is my windows username, however for some reason jupyter.exe installed in
 C:\Users\user\AppData\Roaming\Python\Python37\Scripts

I'm not really sure why and I'd like to get to the bottom of it, but adding both the local and roaming version to my path fixed this.
Comment: Where to check the path?
Answer: Run conda install ipykernel in that environment and then type jupyter notebook, it will lead to jupyter notebook window.
Answer: The issue 'jupyter' is not recognized as an internal or external command is mainly due to no path or wrong path of jupyter in windows environment variables.
In my case related files were available in C:\ProgramData\Anaconda3\Scripts and so i have added this path in Windows as shown below and then you can run from any path:

One important thing: after that while running jupter notebook from any location may give DLL Error. You have to first give command activate base and then jupyter notebook. Enjoy working now.
Comment: adding the correct path worked for me, thanks!
Answer: Just had a similar problem tried it in cmd as well as Powershell, checked other suggestions too. However, the command isn't jupyter notebook it is :
jupyter-notebook
Answer: try typing
> conda install jupyter

inside your environment and then try to open jupyter notebook again.
Answer: You are suppoused to check in the two check boxes which are present at the beginning of installation.If you uninstall and reinstall it again it works fine
Comment: Hi @Chandra, could you please elaborate on the answer you provided? Which check boxes it needs to be checked?
Comment: @ toshiro92 I think he's talking about the checkboxes which appear when we install Anaconda. But I checked both of them still the same problem arised
Answer: If you are facing the issue with the error as below when trying to launch jupyter notebook:

jupyter : The term 'jupyter' is not recognized as the name of a cmdlet, function, script file, or operable program.

Try using below command in TERMINAL:

python -m notebook
Answer: I recently faced this problem and overcame it by below following the command.
If you installed Jupyter Notebook through Commandline or Anaconda.
for Windows 10
First check how your Python is running in command using
Using this command
C:\Users\admin>py

or this command
C:\Users\admin>Python

Most probably your Python starts with the py command.
Now type the below command to run Jypyter
C:\Users\admin>py -m jupyter notebook

or try
C:\Users\admin>python -m jupyter notebook

It'll start jupyter notebook on the browser.
Make sure to add the complete name jupyter notebook. It's working with Windows 10
I hope it helps.
Answer: Here is a supplementary suggestion with respect to @Subhasish Paul 's Answer:
When creating a new path to the user variable (if you chose the option "install for all users" you may need to create a system variable), also include another path of "bin" in your environment variables, simply entering where conda in Anaconda Prompt to look for it. For me it's C:\ProgramData\Anaconda3\Library\bin .
Adding this extra path in your environment variables will eliminate DLL Error, hence you don't have to activate conda each time when you want to open jupyter notebook. It works for me very well.
Answer: Anybody looking to run Jupyter from command line or want to see the token for running Jupyter server (if he/was logged out from running notebook), you run the target command from Jupyter Notebook shortcut ..
Answer: I was also getting:

'jupyter' is not recognized as an internal or external
command,operable program or batch file.

This worked for me on Windows 11
Install Python
Install conda
conda install jupyter
conda run jupyter notebook

Comment: Jai Shah already suggested running `conda install jupyter` a couple of years ago. Please don't repeat answers.
Answer: just run your cmd (or PyCharm, or PowerShell etc.) as Administrator
Answer: Python -m notebook
Use this command
Comment: 1st in cmd type pip install jupyter ,after installation done then type python -m notebook.wait 5 mins jupyter window automatically open .
Comment: Please don't repeat answers.


Django Collectstatic with AWS S3 not copying correct static and media files

Question: I am trying to copy all of my static and media files to an S3 bucket. Unfortunately despite the fact that my media root and static root are provide in my settings.py file....
DEFAULT_FILE_STORAGE = 'jeffrey.aws_storage_classes.MediaStorage'
AWS_ACCESS_KEY_ID = 'keyhere'
AWS_SECRET_ACCESS_KEY = 'secretkeyhere'
AWS_STORAGE_BUCKET_NAME = 'bucketname'
STATICFILES_STORAGE = 'jeffrey.aws_storage_classes.StaticStorage'

AWS_S3_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME
STATIC_URL = "https://%s/static/" % AWS_S3_DOMAIN
MEDIA_URL = "https://%s/media/" % AWS_S3_DOMAIN

MEDIA_ROOT = u'/home/namehere/mysite/media'
STATIC_ROOT = u'/home/namehere/mysite/static'

....files from my django contrib folder seem to be being copied, and my files in static and media folders are not. Below is my bash console:
Type 'yes' to continue, or 'no' to cancel: yes
Copying '/usr/local/lib/python2.7/dist-        packages/django/contrib/admin/static/admin/css/fonts.css'
Copying '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/img/icon-addlink.svg'
Copying '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/img/icon-no.svg'
Copying '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/img/inline-delete.svg'
....
....
Copying '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/img/gis/move_vertex_on.svg'
Copying '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/img/gis/move_vertex_off.svg'
61 static files copied.

Answer: I think the problem lies with your INSTALLED_APPS setting.
It is not wrong for it to copy files from django contrib folder - if you have 'django.contrib.admin' inside of your INSTALLED_APPS setting then it will copy the static files for this such as you have listed above. (This is the Django admin site).
If you don't have your app listed in INSTALLED_APPS then it will skip over collecting static files from your app's folder. I managed to reproduce your problem exactly by removing my app name from this setting, and without a doubt, suddenly it only copied files from django contrib and skipped over my apps static files.
So even if your problem turns out to be different, this will have same effect as you described.
Example: In settings.py you need to ensure you have something that looks like this:
INSTALLED_APPS = [
    # Add your apps here to enable them
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'storages',                     #Amazon S3
    'myapp',
]

Note that 'myapp' will be whatever the name of your app is.


Como comparar strings diferenciando maiúsculas de minúsculas?

Question: Tenho seguinte código:
Usuarios user = DataModel.Usuarios.Where(x => x.Login.Equals(login,StringComparison.OrdinalIgnoreCase) && x.Senha.Equals(senha,StringComparison.Ordinal)).FirstOrDefault();

Gostaria de obter o seguinte resultado:
"login" == "Login" |true|
"senha" == "Senha" |false|

Answer: Você está comparando a senha da seguinte maneira:
x.Senha.Equals(senha, StringComparison.Ordinal)

Segundo a documentação o StringComparison.Ordinal faz a comparação case-sensitive, ou seja, considerando maiúsculas e minúsculas.
Quando você está comparando o usuário, está fazendo assim:
x.Login.Equals(login, StringComparison.OrdinalIgnoreCase)

Não sei a necessidade do uso do OrdinalIgnoreCase no seu caso. Eu sempre utilizo o StringComparison.InvariantCultureIgnoreCase para esse fim, desta forma:
x.Login.Equals(login, StringComparison.InvariantCultureIgnoreCase)

Se puder, vale a leitura de "Difference between InvariantCulture and Oridinal string comparison".
O código que você postou já faz o que você quer. Isso evalua:
"login" == "Login" > true (é case-insensitive)
"senha" == "Senha" > false (é case-sensitive)

Answer: Você pode usar a propriedade InvariantCultureIgnoreCase da classe StringComparer, veja:
string str1 = "Stack";
string str2 = "stack";

Console.WriteLine(str1.Equals(str2, StringComparison.InvariantCultureIgnoreCase));
Console.WriteLine(str1.Equals(str2));

Saída:

True
  False

Veja funcionando no .Net Fiddle.
Comment: Mas o AP perguntou como diferenciar maiúsculas de minúsculas. O `StringComparison.InvariantCultureIgnoreCase` não faz o contrário?
Comment: @vnbrs pelo que eu entendi é para ignorar o case-sensitive, a função acima faz isso, e a debaixo não ignora o case-sensitive.
Answer: Ao passar o parâmetro StringComparison.OrdinalIgnoreCase você está informando para não diferenciar entre maiúsculas de minúsculas, logo:
login == Login // Será verdadeiro se o parâmetro for informado

Mas como pode ver, apesar da palavra ser a mesma, o que diferencia uma da outra é a case-sensitive, veja esse exemplo:
string a = "email@example.com";
string b = "email@example.com";

// Ira retornar Falso, porque não foi informado
// para ignorar case-sensitive
if (a.Equals(b)) {
    Console.WriteLine("Verdadeiro");
} else {
    Console.WriteLine("Falso");
}

// OrdinalIgnoreCase
// Ira retorna Verdadeiro, porque foi informado
// para ignorar case-sensitive
if (a.Equals(b, StringComparison.OrdinalIgnoreCase)) {
    Console.WriteLine("Verdadeiro");
} else {
    Console.WriteLine("Falso");
}

Veja funcionando no dotnetfiddle

Referência

Enumeração StringComparison


Como pegar o nome de uma função callback em javascript?

Question: Por exemplo:
function ola() {
    console.log("Olá =)");
}
function executar(callback) {
    // quero descobrir o nome deste callback que é passado para cá
   callback();
}

executar(ola);

Desse modo, a função executar irá executar (rsrs) o callback que, neste caso, é a função ola(). O que eu gostaria de saber é: como eu posso, dentro da função executar(), ter acesso ao nome real do callback (ola), já que nesse escopo eu apenas uso o alias "callback" para referenciar qualquer função passada como argumento?
Answer: Para ter acesso ao nome: callback.name
function ola() {
    console.log("Olá =)");
}
function executar(callback) {
   console.log(callback.name);
   callback();
}

executar(ola);

Comment: Muito obrigado!


Android proguard rule gives error with twilio client sdk

Question: I have added the Twilio client SDK with the following proguard rules
 # Twilio Client
 -keep class com.twilio.** { *; }
 # Apache HttpClient
-dontwarn org.apache.http.**
-keepattributes InnerClasses

When that's added I get the following set of error message
Warning:library class android.webkit.WebView depends on program class android.net.http.SslCertificate
Warning:library class android.webkit.WebViewClient depends on program class android.net.http.SslError
Warning:there were 3 instances of library classes depending on program classes.
Warning:Exception while processing task java.io.IOException: Please correct the above warnings first.
Error:Execution failed for task ':app:transformClassesAndResourcesWithProguardForRelease'.
> java.io.IOException: Please correct the above warnings first.

To suppress the error I have added these set of rules
-keep public class android.net.http.SslError
-keep public class android.webkit.WebViewClient

-dontwarn android.webkit.WebView
-dontwarn android.net.http.SslError
-dontwarn android.webkit.WebViewClient

When I do the above I get these set of errors
Error:warning: Ignoring InnerClasses attribute for an anonymous inner class
Error:(android.support.design.widget.o) that doesn't come with an
Error:associated EnclosingMethod attribute. This class was probably produced by a
Error:compiler that did not target the modern .class file format. The recommended
Error:solution is to recompile the class from source, using an up-to-date compiler

which breaks the apk build. Any sort of help will be appreciated. TIA
Answer:
Error:warning: Ignoring InnerClasses attribute for an anonymous inner class
Error:(android.support.design.widget.o) that doesn't come with an
Error:associated EnclosingMethod attribute. This class was probably produced by a
Error:compiler that did not target the modern .class file format. The recommended
Error:solution is to recompile the class from source, using an up-to-date compiler

To solve innerclass issue add this in your proguard file:
-keepattributes EnclosingMethod

Comment: Can you please brief more on the solution?


Can menuTree load a menu's items including children

Question: From what I understand I should be able to retrieve all the items in a menu using menuTree. However I only get one level/depth no matter what I try.
My Menu Looks Like:

Imported Content
--Products
----A Child
------Grand Child
--------Great Grandchild
------Grand Child 2
----Child 2
--A Sibling

Menu structure (screenshot): https://www.evernote.com/l/AAKdnwekb7BM87AFANo1z2XjCdEvR8HgDEI
This is my code:
  $menu_name = 'imported-content-menu';
  $menu_tree = \Drupal::menuTree();
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
  $parameters->setMaxDepth(100);
  $parameters->setMinDepth(0);
  $tree = $menu_tree->load($menu_name, $parameters);

When I inspect $tree, it is an array of two items "Products" and "A Sibling".
I inspected these two items to see if there were nested items (the children) but there were not.
The "Products" item has 'hasChildren' set to TRUE. But I don't see those children.
Comment: Since hasChildren is true and maxDepth is plenty deep I believe there should be a $tree[%pluginid]->subtree array. However, my subtree array exists but is empty. To debug I took the pluginid for 'Products' and use it in setRoot. I got an empty tree. Maybe my issue is these children can't be loaded for some reason. I am not using access manipulators. Any tips how to debug this would be greatly appreciated.
Answer: Within the typical route context ($menu_tree->getCurrentRouteMenuTreeParameters($menu_name)), subtree elements are loaded only, if the menu item is flagged as "Show as expanded" within the menu item settings.
To load the entire tree, you have to pass in a plain MenuTreeParameters object without the current route context:
use Drupal\Core\Menu\MenuTreeParameters;

$parameters = new MenuTreeParameters();

// Optionally limit to enabled items.
$parameters->onlyEnabledLinks();

// Optionally set active trail.
$menu_active_trail = \Drupal::service('menu.active_trail')->getActiveTrailIds($menu_name);
$parameters->setActiveTrail($menu_active_trail);

// Load the tree.
$tree = \Drupal::menuTree()->load($menu_name, $parameters);

Comment: You have no idea how much thanks I have to give! Thank you!!! This was the issue.


Reasoning behind: local variable 'derived' will be copied despite being returned by name

Question: This is a follow up to Is -Wreturn-std-move clang warning correct in case of objects in the same hierarchy?, because I don't understand reasoning in certain specific cases.
struct Field {
  Field();
//  Field(const Field&); // (a)
  int a[1000000];
};

struct Base
{
  Base();
//  Base(const Base&); // (b)
//  Base(Base&&); // (c)
  Field f;
};

struct Derived : Base { };

Base foo()
{
  Derived derived;
  return derived;
}

The above code compiles just fine. I understand, std::move wouldn't do anything different.
Uncomment (a), you get the warning. Why? I believe std::move still won't do anything different.
Uncomment (b) (keep (a) uncommented), works fine again. How is it any different than #2?
Uncomment (c) (keep (a) and (b) uncommented), shows warning again. This makes sense, std::move could save us a copy.
Have foo return Derived, works fine again. How is it any different than #4?
Answer: As state in link answer, and in cppreference
We first consider derived as rvalue, and if it doesn't select XXX(/*const*/Derived&&) (until C++20) then we reconsider it as lvalue.
So as long as there are no Base(Derived&&), a copy is done.
I didn't find the whole logic of the warning though., 1. 2. 3. should be treated the same IMO (either no warnings as currently equivalent, or warning for future proof).
For 1.
copy and move constructor are generated by compiler.
copy or move give same result at the end.
For 2.
Field move constructor is non longer generated, making the whole chain copy instead of move.
copy or move give same result at the end.
For 3.
Base move constructor is non longer generated, making copy from the start.
copy or move give same result at the end.
For 4.
Base has both copy and move constructor.
copy or move give different result.
For 5.
We now have match XXX(Derived&&) (XXX=Derieved), so no copy done.
Comment: It all makes sense, thanks for explaining! I'm also pondering why is #2 different than #1&3. I just had one silly thought: [cppreference](https://en.cppreference.com/w/cpp/language/move_constructor) describes implicit construction declaration and deletion in two sections; is there a behavior difference depending on which section it falls under? #3 falls under not-even-declared category, whereas #2 falls under deleted category.
Comment: We don't have delete move constructor here, and indeed, we should not have warning when `return std::move(derived)` is ill formed.


Receiving a TypeError when using scipy.integrate.quad: "Can't convert complex to float"

Question: I am trying to integrate a function that includes a complex number.
I have tried separating the integral into real and imaginary integrals, but I receive an error for that as well.
This is the integration I am attempting to perform:
<code>def H(G):
    return integrate.quad(lambda x: (np.pi*(np.exp(-x)))/(1+1j*G),0,np.inf)
scipy.optimize.fsolve(lambda G: f(G),x0 = 1)
</code>
I continue to receive a TypeError message:
<code>"Can't convert complex to float"
</code>
and I do not understand how to reconcile it. Thanks!
Answer: fsolve deals with real-valued functions of real arguments.
Comment: Is there a way to separate the integrand into complex and real integrands? Or is the a method to solve equations including complex values?


Bounding fractional moments of geometric random variable

Question: The following two bounds for a fractional moment of a geometric random variable $X$ with $\mathbb{P}\left[X = k\right] = p \left(1 - p\right)^k$ where $k \geq 0$ are given in this paper (on page 12):
Let $s \in \left(0, 1\right)$, then

$\mathbb{E}\left[ X^s \right] \leq C_1\left(s\right) p^{-s} \left(1 - p\right)$, and
$\mathbb{E}\left[ X^{-s} \mathbf{1}_{\left\{X > 0\right\}} \right] \leq C_2\left(s\right) p^s \left(1 - p\right)$

where $C_1$ and $C_2$ are constants depending only on $s$ (these inequalities can be expressed in terms of the polylogarithm, see below).
I would appreciate any help in showing that the 2nd bound is true. I do know how to prove the first bound, but the same method fails for the 2nd. You can show the first one by noting that $f\left(s\right) = \mathbb{E}\left[ \left(p X\right)^s \right]$ is convex and continuous in $s$, and can be continued to the interval $s \in \left[0, 1\right]$ with $f\left(0\right) = f\left(1\right) = 1-p$. By convexity, $f\left(s\right) \leq 1 - p$ for all $s \in \left(0, 1\right)$, which proves the bound with $C_1\left(s\right) = 1$.
Trying the same method on the 2nd bound yields the convex and continuous function $g\left(s\right) = \mathbb{E}\left[ \left(pX\right)^{-s} \mathbf{1}_{\left\{X > 0\right\}} \right]$ with $g\left(0\right) = 1-p$, but $g\left(1\right) = - \ln\left(p\right)$ (see this post), so we cannot get a constant $C_2$ which is independent of $p$ in this way.
Note that $\mathbb{E}\left[ X^s \right] = \sum_{k \geq 0} k^s p\left(1-p\right)^k = p \cdot \sum_{k \geq 1} \frac{\left(1-p\right)^k}{k^{-s}} = p \cdot \textrm{Li}_{-s}\left(1-p\right)$ where $\textrm{Li}$ denotes the polylogarithm, and $\mathbb{E}\left[ X^{-s} \mathbf{1}_{\left\{X > 0\right\}} \right] = p \cdot \textrm{Li}_{s}\left(1-p\right)$. So useful references on the behavior of the polylogarithm would also be appreciated.
Looking at plots on WolframAlpha (I plotted $\frac{p^{1-s}}{1-p} \textrm{Li}_{s}\left(1-p\right)$, which should be smaller than $C_2\left(s\right)$) shows that the critical region for the bound to be true is $p \to 0$, and indeed calculating the limit on WolframAlpha confirms that such a constant $C_2\left(s\right)$ should exist, and also that the behavior of the polylogarithm seems to be better understood than what I could get from my internet researches.
Answer: One way of showing the second bound is the following:
Let $Y \sim \textrm{Geo}(p)$ be a random variable with geometric distribution of parameter $p$, but which takes values in $\mathbb{N} \setminus \left\{0\right\}$, so $\mathbb{P}\left[Y = k\right] = q^{k-1} p$ where $k \geq 1$ and $q = 1 - p$. Then we can write
\begin{align}
    \label{eq:scnd_sum_bound}
    q \cdot \mathbb{E}\left[Y^{-s}\right] = q \cdot \sum_{k \geq 1} k^{-s} q^{k - 1} p = \sum_{k \geq 1} k^{-s} q^k p = \mathbb{E}\left[X^{-s} \mathbf{1}_{\left\{X > 0 \right\}} \right] &\leq C_2\left(s\right) qp^s \\
    \iff \mathbb{E}\left[\left(pY\right)^{-s}\right] &\leq C_2\left(s\right)
  \end{align}
Now, $g\left(p\right) = \mathbb{E}\left[\left(pY\right)^{-s}\right]$ is decreasing in $p$ (to see this, note that
$\mathbb{E}\left[\left(pY\right)^{-s}\right] = \frac{p^{1 - s}}{1 - p} \cdot \textrm{Li}_s\left(1 - p\right)$, derive: https://bit.ly/3BOmLjP,
and analyze the derivative: https://bit.ly/3RVn5CA), so it is sufficient to show that
$\lim_{p \to 0} g\left(p\right) =: C_2\left(s\right)$ exists and is finite. Note that for $p \to 0$,
$pY$ converges in distribution to a random variable $Z$ which is $\textrm{Exp}\left(1\right)$-distributed
(we have that $\mathbb{P}\left[pY > t\right] \to e^{-t}$ for $p \to 0$). Therefore, $\lim_{p \to 0} g\left(p\right) = \mathbb{E}\left[Z^{-s}\right] = \Gamma\left(1 - s\right) < \infty$
for $s \in \left(0, 1\right)$. Thus, we can choose $C_2\left(s\right) = \Gamma\left(1 - s\right)$.


Como faço para encontrar parte de um elemento dentro de um array? (Javascript)

Question: Estou fazendo um filter dentro de um array para pegar parte do elemento conforme  digitado na minha busca onde:
array.filter(row => row.cnpj.indexOf(search) >= 0)

Considerando 'search' a busca digitada, se tiver dentro do array, cnpj com valor nulo vai dar erro no indexOf:
TypeError: Cannot read property 'indexOf' of null

Como eu faço esse filter ignorando os valores nulos ou então existe uma maneira melhor de fazer isso?
Comment: Será que podias mostrar o resto do código para se perceber mais facilmente o problema?
Answer: Achei a resposta:
value.filter(row => {
   const cnpj = row.cnpj || ''
   return cnpj.indexOf(this.search) >= 0
})

Era apenas colocar o valor esperado pelo indexOf numa const
Comment: Talvez te ajude usar o método [includes](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/includes) em vez de indexOf.


PromiseRejectionEvent occurence depends on the reject parameter type (primitive vs Error)

Question: CODE 1:
function unhandledrejection(event)
{
    console.log("unhandledrejection: ", event.promise);
    console.log("unhandledrejection: ", event.reason);
}
window.addEventListener('unhandledrejection', unhandledrejection);

var promise = new Promise((resolve, reject)=>reject(new Error("Oops")));

promise.then(value=>console.log(value));

Debug console:
Uncaught Error: Oops
CODE 2
var promise = new Promise((resolve, reject)=>reject("result"));

promise.then(value=>console.log(value));

Debug console:
unhandledrejection: Promise...
unhandledrejection: result
Uncaught result
So why does string in rejection send PromiseRejectionEvent but Error does not?
Comment: must be a chrome/chromium bug - worlds most popular browser means they don't need to make it work properly any more
Comment: I cannot reproduce with this code in a HTML file, but can reproduce with this code in DevTools. So it seems this is the same issue as in https://bugs.chromium.org/p/chromium/issues/detail?id=1111093
Comment: Thanks. My HTML reproduces the "bug" in Edge and Opera.
Answer: I can't reproduce the different behavior you describe. For me, both cases seem consistent. I've tried this in Chrome and Firefox.
Let's consider these two rejected promises:
Promise.reject( 'bad' )
Promise.reject( new Error('also bad') )

Unhandled-rejection handlers receive an event whose .reason property is whatever value the promise rejected with. In our first example, .reason will be the string "bad"; in our second example, it will be an Error instance (whose .message is "also bad").

I should also note that your example code chains promises using .then. However, if the first promise rejects, the .then handler will not execute. This is by design.


Proving the limit of the sequence for $\lim{a_nb_n} = ab$

Question: the part of my proof that I am not sure is ok.
Let $\epsilon > 0$ Suppose $\lim{a_n}= a$ and $\lim{b_n}= b$. Since $\lim{a_n} = a, \exists N$ s.t. for $n>N$, $
|a_n-a|< \epsilon/2|b|$
and I will use the triangle inequality to complete an N epsilon proof. I just am not sure if it is ok to use $\epsilon/2|b|$ as by $n(\epsilon)$ . To me it does not seem well defined in this abstract proof.
Comment: Presumably $a_n \to a, b_n \to b$? You should ask a complete question.
Comment: No. If you do it this way, you need to split the proof into at least two parts.
Comment: you can't divide by 0, so if b=0 we can use b+1 instead
Comment: you are correct, will add that assumption, so does this assumption allow me to  have b in denominator even if b=0?
Answer: what if b=0? and also is it given that a and b are the limits of $a_n$ and $b_n$.
then try to use the fact that converging sequences are bounded and $a_nb_n-ab=a_n(b_n-b)+b(a_n-a)$


Help Understanding Chord Progression

Question: Hoping someone can explain this chord progression to me, I'm used to standard progressions such as I > IV > 5 etc.
Cmi9 > Ab9 > Cm11 > C7(#9,b13)
Would this be essentially I > vi > I > I?
Thrown off by the Ab dominant 9th chord, is this chord in the key of C?
Bit of an open question but any insight into how this chord progression would be named would be fantastic.
Thanks
Comment: @gui3 Ab9 has a Gb in it :s
Comment: what happens after C7?
Comment: A *dominant* 9 or Ab *dominant* 9? And it certainly won't be 'vi'. And - don't get fooled by 'chords must be in a key'.
Comment: Hi Tim, Ab dominant 9 sorry. I suppose the chords don't fit within a key but sound nice together regardless
Comment: These chords (especially the first 2) sound the same, the bass note changes but the other notes don't change (and change few after). Nothing to do with your question, though
Comment: @JudyN. i'm stupid I played a AbM9, it's not like there was a precision about it being dominant... Sorry
Answer: In fact Ab major lies very much "within" the sound world of C minor and will crop up in many many pieces in C minor. What is unusual is that it is a dominant chord, and so contains a Gb, which is a very "outside" tone in C minor. One illustration of how a plain Ab major would be "within" C minor can be seen towards the end of the progression: the C dominant is setting up a move to F minor, and Ab major is the relative major of F minor. However as I said the Gb is a very strong "colour" tone making this progression sound quite novel/distinctive
Answer:
Thrown off by the Ab dominant 9th chord, is this chord in the key of
C?

As long as C stays the home note and C minor stays the home chord, you can consider being in the key of C minor. It really doesn't matter what notes or chords are played, if playing them doesn't disturb your sense of home chord.
"This song is in C minor" means three things: (1) home note is C, (2) home chord is C minor, (3) the default basic scale is C natural minor, with three flats in the key signature. If your sense of home doesn't change, then the key doesn't change. You can literally play any notes, and they will cause some temporary pressure and feelings, without necessarily changing the key.
Some people like to think of "key" as being one single scale, but such a definition won't really stand the light of day, when exposed to actual music. It's extremely common to have non-diatonic notes in melodies and harmonies. C - F - D7 - G - C. These are denoted with accidentals in music - and as you know from musical notation, accidentals are temporary. Permanent sharps/flats are written in the key signature. This notational convention just reflects the way music works. Most notes outside the basic scale can be written with temporary accidentals, because the sharpening/flattening of that note is temporary anyway.
If you play the Ab9 chord for a minute, and then play a C#m chord for another minute, then your sense of home chord probably changed. But in a chord progression like the one you posted, that's not the case.
When the only tool you have is a hammer, you want everything to be a nail. The functional harmony model with Roman numerals etc is a simplified educational tool, For Dummies, My First Harmony Thing. Instead of demanding everything to look like the basic structural example from theory classes, look at and experiment with what happens in the harmonic context at every chord change. What happens when that Ab9 chord is played is, the G note is temporarily flattened, and a soloist probably shouldn't try to play a G natural note over that. (YMMV of course) But it doesn't need to cause any more side-effects.
Comment: This was extremely helpful and a bit of an eye opener! Thanks very much for taking the time to explain this in great detail I really appreciate it.
Answer: Playing/hearing the progression is perhaps the best way to understand the "how" of it.
In addition to key (C minor, as others have explained), it can be helpful to understand the chords in terms of voice-leading; that is, how one chord voicing proceeds to the next and leads the ear through the progression.
For example:

Cm9 contains G;
Ab9 contains Gb;
Cm11 contains F;
C7(#9b13) contains E.

A couple points of interest:

Aside from the initial G, each of the tones proceeding chromatically downward is unique to its chord within the progression.
Note also how Bb and Eb(D#) are maintained across the progression, lending stability to the sound.

X:1
T:Cm9 => Ab9 => Cm11 => C7(#9b13)
T:G - Gb - F - E chromatic descent
K:none
M:none
L:1/1
[V:V1] "_G""^Eb/Bb"[G_B_e] "_Gb""^Eb/Bb"[_G_B_e] "_F""^Eb/Bb"[F_B_e] "_E""^'Eb'/Bb"[E_A_B^d] |
[V:V2 clef=bass] "_Cm9"[C,C] "_Ab9"[_A,,C] "_Cm11"[C,D] "_C7(#9b13)"[C,C]     |

To emphasize the "key of C-ness" of the progression, you could re-voice/reinterpret the chords to produce a C pedal tone. In this case Ab9 becomes Cm7b5b13.
Two more points of interest:

Notice here that the upper voices from the previous example are preserved.
Also notice the alternating Bb/Ab in the tenor voice.

X:1
T:Cm9 => Cm7b5b13 => Cm11 => C7(#9b13)
T:C pedal tone
K:none
M:none
L:1/1
[V:V1] [G_B_e] [_G_B_e] [F_B_e] [E_B^d] |
[V:V2 clef=bass] "_Cm9""^Bb"[C,_B,] "_Cm7b5b13""^Ab"[C,_A,] "_Cm11""^Bb"[C,_B,] "_C7(#9b13)""^Ab"[C,_A,]     |

There are quite a few voice-leading patterns embedded in this chord sequence, especially when you allow for re-voicing/reinterpreting the chords. Another option emphasizes the alternation between G and Ab. In fact, not just G and Ab, but the G/Bb => Ab/C dyad alternation, again while preserving the voice-leading in the upper part.
X:1
T:Cm9 => Ab9 => Cm11 => C7#9/Ab
T:G/Ab bass alternation
K:none
M:none
L:1/1
[V:V1] [G_B_e] [_G_B_e] [F_B_e] [E_B^d] |
[V:V2 clef=bass] "_Cm9""^Bb"[G,_B,C] "_Ab9""^C"[_A,C] "_Cm11""^Bb"[G,_B,C] "_C7#9/Ab""^C"[_A,C]     |

Help Understanding Chord Progression


gnuplot map view customizing color

Question: As seen, the default colour in map-view in Gnuplot for zero value  is black. I want to make it white and display other colours for other data. May you tell me how to customise the colours please? Thank you.
Answer: See the help for palette:
gnuplot> help set palette

After setting the palette, you give for example with points palette to the splot command.
Comment: I have done this: [set view map;splot '1.dat'u 1:2:0.0:3 with points palette] It takes black colour for the zero values and rest for the other data. I want the zero value to be white. May you tell me what is lacking to this please?
Comment: @ndphysics: You need to `set palette ...`.  If you start gnuplot by entering just `gnuplot` on a shell, you get the gnuplot prompt (`gnuplot>` above).  There, you enter `help set palette` to find out how to use that.  Alternatively, download http://www.gnuplot.info/docs_4.4/gnuplot.pdf and look at chapter 75.53 on page 131.

gnuplot map view customizing color


Pointwise infimum of an arbitrary collection of upper semicontinuous functions is upper semicontinuous

Question: A real-valued function $f:X \rightarrow \mathbb{R}$ is upper semicontinuous if for each $c \in \mathbb{R}$, its pre-image $f^{-1}(-\infty,c)$ is open in $X.$
In encyclopaedia, there is the following statement:

Let $\mathcal{F}$ be an arbitrary family of upper semicontinuous functions on a given topological space $X$. Then the function $F(x) = \inf_{f \in \mathcal{F}} f(x)$ is upper semicontinuous.

The article stated that the proof can be found in General Topology by Bourbaki, Chapter $5 - 10$. But I do not have access to that book.
In Wikipedia, similar statement appears.

Likewise, the pointwise infimum of an arbitrary collection of upper semicontinuous functions is upper semicontinuous.

I manage to prove the statement holds for countably many functions, its proof is similar to proving infimum of measurable functions is measurable, but I have no idea on how to prove for arbitrary case.
Comment: See also: [Show that the supremum of a collection of lower semicontinuous function is lower semicontinuous](https://math.stackexchange.com/q/2320814) and [To show that the supremum of any collection of lower semicontinuous functions is lower semicontinuous](https://math.stackexchange.com/q/1662726)
Answer: $$F(x)<c\iff\exists f\in\mathcal F [f(x)<c]$$
so that: $$F^{-1}(-\infty,c)=\bigcup_{f\in\mathcal F}f^{-1}(-\infty,c)$$
If the $f\in\mathcal F$ are upper semi-continuous then this is a union of open sets, hence is open.


Replacing Month Name with its respective Month Number

Question: I am trying to replace a month value in a <month> tag to its respective month number for example : <month>Feb</month> should be replace with <month>02</month>
I have tried this,
Dim strFile As String = File.ReadAllText(TextBox1.Text & "\" & parentFolder & ".xml")
    strFile = Regex.Replace(strFile, "<conf-start.*?><day>(.*?)</day><month>Feb</month>", "$&<month>02</month>")
    File.WriteAllText(TextBox1.Text & "\" & parentFolder & ".xml", strFile)

But it is giving me the below output
<conf-start iso-8601-date="0"><day>00</day><month>Feb</month><month>02</month>

Instead its adding tag next to month name the output i wanted is as follows,
<conf-start iso-8601-date="0"><day>00</day><month>02</month>

Month name should be replaced with its respective number.
Thanks in advance..
Comment: Don't use regex to deal with XML/HTML...
Comment: Could it be you're asking the same question twice? Please revise one question and close/delete the other.
Answer: Use XDocument it's easy to figure out.  Then just parse the node contents with either
DateTime dateTime = DateTime.ParseExact("November", "MMMM", CultureInfo.CurrentCulture);
DateTime dateTime = DateTime.ParseExact("Nov", "MMM", CultureInfo.CurrentCulture);
depending on the format of the month.  That'll give you a date like 11/1/2014 12:00:00 AM.  I was a little surprised the year is current and not the epoch but we don't care.
Then
dateTime.Month.ToString() to replace the node content.
The DateTime trick doesn't like "." on abbreviated months in the second case but you sample doesn't contain that.  If it comes up use dateString = dateString.TrimEnd('.') to get rid of the "."


Convert Uploaded Files To .pdf

Question: I'm reviewing a spec. that calls for all files uploaded via a file field to be automatically converted to PDF format.  I have two questions:

Is this wise?  Files would be uploaded by anonymous customers.  Allowed file extensions (.doc, .xls, .png, .jpg, etc) would be provided as per normal file field use.

(Edited to clarify my main concern is security)

Are there any conversion tools you would recommend?  Paid or free is fine.  Remote service is fine, local server-based is preferable.  I can't find anything in the Drupal-verse, but have uncovered tools such as unoconv and JODConverter that look promising.
Answer: Personally, I would store the file as it was uploaded, and then render it as a PDF for users when they download it.  Your spec may say PDF now, but you want to have the flexibility should things change in the future.
Is this a good idea?  That is a tough question, and really depends on the exact scenario.  Personally, I would push back on this requirement.  Format conversion can tax system resources, and I don't think you can really constrain the .doc and .xls formats enough, like you can with images, to be something reasonable.
Tools?  The Printer, email and PDF versions module has a list of of the PHP-based PDF modules:

dompdf
mPDF
TCPDF
wkhtmltopdf

I am unaware if any of these will support .doc or .xls formats.  I have used Ghostscript to convert images to PDF, and I am pretty sure it has some support for .doc.  I am unaware of any Drupal-ready solution for this, though.
As for security implications, the scenario "makes my spidey sense tingle", but I can't point to anything in particular.  I don't think you would have any problems with any of the malicious payloads in .doc and .xls files that normally affect Windows machines.  However, if you go with a solution like GS, you will have to use a popen() or something similar, so you run the risk of an exploit there.
Comment: Thanks for the feedback MPD.  My main concern re: this being a good idea is around security.  These are anonymously uploaded files.  Performance is less important.
Answer: See if https://github.com/delphian/drupal-convert-file/wiki fits your needs. It will make a backup of the original file, and uses remote providers (currently google drive) to do the actual file conversion. The google drive provider will convert .doc .xls and .txt to .pdf.
Comment: Have you tried the github project yourself? Why is it not a drupal.org project, is it stable enough>

Convert Uploaded Files To .pdf


Simplifying ratio test with exponents $k+1$

Question: Question: Find the interval and radius of convergence. $$\sum_{k=1}^\infty\frac{(x-1)^k(k^k)}{(k+1)^k} .$$
I applied the ratio test.
$$r=\lim_{k\to\infty}\frac{(x-1)^{k+1}(k+1)^{k+1}}{(k+2)^{k+1}}\times\frac{(k+1)^k}{(x-1)^k(k^k)}\ .$$
I am stuck here. Please help me simplify.
Comment: i will use root test.
Answer: $\bigg(\dfrac{k + 1}{k + 2}\bigg)^{k+1} = \dfrac1{\bigg(1 + \frac1{k+1}\bigg)^{k+1}} \to \dfrac1e,\quad$ and $\quad\bigg(\dfrac{k + 1}k\bigg)^k = \bigg(1 + \dfrac1k\bigg)^k \to e.\quad$ So you have $r = |x - 1| < 1 \iff 0 < x < 2$.
Answer: it is easyier to apply Cauchy (n-th root) test.
$\sqrt[k]{\frac{|x-1|^k.k^k}{(k+1)^k}}=|x-1|\frac{k}{k+1} \to |x-1| <1$
Comment: this helps a lot!


Enviar email PHP+CodeIgniter

Question: Pessoas, fiz vários exemplos, sendo eles de livros ou da internet e todos retornam o seguinte mensagem quando executo a função para enviar o email:
Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
Poderiam por favor explicar o que é esse SMTP? E o que eu deveria fazer para funcionar?
Obrigado.
Comment: [Dificuldades no Envio de E-mail usando PHP](http://pt.stackoverflow.com/a/67017/91)
Answer: Simple Mail Transfer Protocol (abreviado SMTP. Traduzido do inglês, significa "Protocolo de transferência de correio simples") é o protocolo padrão para envio de e-mails através da Internet.
Você pode postar trecho do seu código para que possamos analizar melhor seu problema?
Mas responda algumas perguntas: Você quer enviar e-mail no seu localhost? ou já possui um servidor web configurado ?
Comment: Olá, já consegui resolver, agradeço a sua ajuda.

Enviar email PHP+CodeIgniter


OPENQUERY on SQL Server 2005 64bit behaves weird

Question: I just recently moved a SQL DB from SQL2005 32 bit --> 64 bit. I am having an issue connecting to Oracle using the OraOLEDB.Oracle Provider.
I was able to install Oracle 10G Client , ODAC 64 bit. I was also able to add a linked server to the Oracle instance. I am able to run a query using the linked server name directly:
SELECT top 10 *
  FROM [DB0PBB0]..[DB0PBB0].[DM_CLICK]

So far it is good, however, the problem occurs when I try to use OPENQUERY. I tried the following:
select * from
OPENQUERY(DB0PBB0,'select *  from DB0PBB0.DM_CLICK where Date_stamp <''24-Jul-09'' and Date_stamp >= ''23-Jul-09'' ')

SET FMTONLY OFF
select * from
OPENQUERY(DB0PBB0,'select * from DB0PBB0.DM_CLICK where Date_stamp <''24-Jul-09'' and Date_stamp >= ''23-Jul-09'' ')

and I get only the column names, no rows :(
if I run this script:
SET FMTONLY OFF
select * from
OPENQUERY(DB0PBB0,'select ''hello'' from dual ')

I get

hello

My question is, has anyone tried running OPENQUERY against Oracle from a SQL05 64bit ? Any ?Idea why would I get only columns back instead of data? I tried the same query on another server with the same link and it worked, it returned rows.
Answer: since you are getting rows with the SELECT * FROM DUAL chances are that it is a query issue. Regarding your query one potential pitfall is that you are comparing what looks like a date column (DATE_STAMP) with a VARCHAR.
You should not rely on implicit conversions to compare dates. Instead you should use the appropriate explicit functions, for exemple:
select * from
OPENQUERY(DB0PBB0,'select *
                     from DB0PBB0.DM_CLICK
                    where Date_stamp < to_date(''24-Jul-09'', ''dd-mon-rr'')
                      and Date_stamp >= to_date(''23-Jul-09'', ''dd-mon-rr'')')

Comment: Thank you very much.Because of your answer, I was able to use the OLEDB driver instead of the OLEDB-ODBC Wrapper


Given differentiable $f$ with $f(0)=0$, $f''(0)>0$ prove there exists $x > 0$ such that $f(2x) > 2f(x)$

Question: Let $f : \mathbb R \to\mathbb R$ be a differentiable function such that $f(0) = 0$, and $f''(0)$ exists and is positive. Prove that there exists $x > 0$ such that $f(2x) > 2f(x)$.
By Taylor's theorem with Lagrange's reminder I can write
$$f(x)=xf'(0)+x^2f''(0)/2+x^3f'''(y)/6$$
with $0<y<x$, so if I write $g(x)=f(2x)-2f(x)$ I have
$$g(x)=x^2f''(0)+x^3f'''(y).$$
If $f'''$is bounded in $(0,h)$ for some $h>0$, then
I have $g(x)/x^2$ tends to $f''(0)>0$ as $x$ tends to 0, and by the limit definition $g(x)>0$ for some $x$ small enough, and we're done. However we don't have conditions for $f'''(x)$ to be bounded near 0, so I don't know how to get $g(x)>0$ near 0.
Comment: How do you know its thrice differentiable?
Comment: FYI, mathjax works in titles too
Answer: Let $g(x)=f(2x)-2f(x)$, so $g(0)=0$ and $g'(x)=2f'(2x)-2f'(x)$ so $g'(0)=0$. Finally, $g(x)=\frac{g''(0)}{2}x^2+o(x^2)$ which in turn gives $g(0)>0$ for $x \in (0,\varepsilon)$ since it behaves like a degree two polynomial with positive degree two coefficient close to zero. That gives you the answer and you don't need to assume any more differentiability for $g$.
Comment: But again @ArcticChar , $f$ is not under hypothesis since it is not differentiable at zero.
Comment: This answer gave an hint, from which I solved the problem, since it can be shown, without Taylor's expansion, that if g(0)=g'(0), and g"(0)>0, with g differentiable, then g(x)>0 for some x (which is my previous post). It is wrong in the second part (the Taylor expansion).
Comment: @astro you can't assume $f$ is smooth.
Comment: By differentiable I just meant that the first derivative exists everywhere, with no statement about the higher order derivatives.
Comment: When you write $g(x) = \frac{g''(0)}{2} x^2 + o(x^3)$, do you need to assume that $g$ is three times differentiable?
Comment: If you knew it, it would be straighforward that that holds. If you don't know it, you can make an $\varepsilon - \delta $ argument regarding $|g(x)-\frac{g''(0)}{2}x^2|$ to show that they are close so an analogous property to the former follows. Moreover, when your hypothesis says ''given $f$ differentiable'', how differentiable is that $f$? You may assume $f$ is smooth under that general assumption.
Comment: I am asking since you claimed that you don't need more differentiability assumptions on $g$. From the question I suppose $f$ is differentiable, and $f'$ is differentiable at $x=0$.
Comment: Is not a problem, take $f(x)=x^2 + \sqrt{x^5}$, it fulfills all the conditions and is not three times differentiable. Anyway, you should be a little more careful when you say differential so loosely, it could mean very different things in different contexts (for example, my function here is not ''differentiable'' in any open set containing zero, so there you go).
Comment: Yes. Using your $f(x) = x^2 + x^{2.5}$, the corresponding $g$ does not satisfy $g(x) = \frac{g''(0)}{2} x^2 + o(x^3)$. Let's what I want to point out.
Comment: The first part of this answers transforms the problem in the other I posted before, where I didn't need to use Taylor's expansion formula, otherwise I couldn't say that the reminder is o(x³) without assuming some conditions on the third derivative, which was the matter of this question.
Comment: Exactly @PierFrancescoPeperoni , that is why I am saying\asking what OP means when he says that $f$ is ''differentiable''.
Comment: @PierFrancescoPeperoni So in some sense this answer did not answer this question
Comment: I forgot g(0)=g'(0)=0
Comment: First of all I think you should give a precise meaning of '''differentiable'', does it mean infinitely differentiable? smooth? Looking at your request it looks like it is but again, is not really absolutely clear. On the other hand, you're both correct when you said $o(x^3)$ is wrong, I should have written $o(x^{2+\alpha})$ for some $\alpha >0$. In the case of $f(x)=\left\{ \begin{array}{c} x^2 + \sqrt{x^5} \mbox{ if x \geq 0}\\  x^2 + \sqrt{(-x)^5} \mbox{ if x<0} \end{array}\right.$ you have a full example holding for all positive $\alpha < 1/2$.
Comment: A better aproach would be to use that, if you knew $ f \in C^2$, continuity of $f''$ and Lagrange's remainder theorem with the equality $g(x)=r_2(x)$ for the remainder yields the property in a better shape than any of the above.
Comment: By [Taylor's theorem with Peano's form of remainder](https://math.stackexchange.com/q/1809293/72031) your answer needs the hypotheses that $g''(0)$ exists (equivalently $f''(0)$ exists). Need not worry at all. +1
Answer: At $x=0$, $f(2x)$ and $2f(x)$ are both $0$ and equal.
At $x=0$, their derivative are both $2f'(0)$ and equal.
At $x=0$, their derivative is increasing as $f"(0)>0$.
The double derivative of the former is $4f''(0)$, is larger than that of the latter, $2f''(0)$.
Hence at a point "close" to 0, the derivative of the former increases faster than the latter, and as they both start from the same point, the former has a value larger than the latter for a point "close" to 0.
To be more "rigorous", you may follow the same procedure by defining a function $g(x)=f(2x)-2f(x)$ and show that it is positive at some point(but I would prefer the more logical approach as above :) )
Answer: I'll assume the following: $f$ is differentiable in a neighborhood of $0,$ and $f''(0)>0.$ We do not need the existence of $f''$ anywhere else and we certainly don't need the existence of $f'''$ anywhere.
From Taylor we then have
$$f(x) = 0+ f'(0)x + f''(0)x^2/2 +o(x^2).$$
Thus
$$f(2x)= 2f'(0)x + 2f''(0)x^2 + o(x^2),$$
whereas
$$2f(x) = 2f'(0)x +f''(0)x^2 + o(x^2).$$
Subtracting, we get
$$f(2x) - f(2x) = f''(0)x^2 + + o(x^2).$$
Because $f''(0)>0,$ the last expression will be positive for small nonzero $x.$
Comment: Don't you need f'''(x) to be bounded around 0 to say that the reminder in Taylor's expansion is o(x²)?
Comment: No you don't. Lemma: Suppose $g(0)=g'(0)=g''(0)=0.$ Then $g(x)=o(x^2).$ Proof: MVT appled twice.// So if $f$ is differentiable near $0$ and $f''0)$ exists, apply the lemma to $g(x) = f(x)-(f(0)+f'(0)x+f''(0)x^2/2).$


Guitar buzzing after replacing bridge pickup

Question: I replaced my humbucker bridge pickup with a different one (humbucker as well) and now I have this buzzing when I'm not touching any metal part on my guitar (string or pots). I wired the pup exactly as the previous one was and did not touch anything else.
I checked with a multimeter and all seems to be grounded well (including the bridge ground cable) and nothing seems to be shorted. Once I touch a metal part the buzz stops completely.
Any suggestions? This is very frustrating!
Answer: I found this very helpful link: http://www.guitarnuts.com/wiring/shielding/shield3.php and I found out I had ground loops; removing them improved the issue a lot. There is much more shielding stuff to do in this link, requiring more material and time, so I definitely recommend it.


How to create search indexes by path in Drupal 8?

Question: For a relatively small Drupal 8 website, I need to enable a search box, with multiple indexes based on the path or menu value.
For example; the main menu has 2 menu items linking to basic pages: Employers and Employees, and rest of the website pages are created under these two pages, and each page has a menu item with matching hierarchy.

Employers

Section A

Sub-section A-1
Sub-section A-2
Sub-section A-3

Section B

Sub-section B-1

Section C

Sub-section C-1
Sub-section C-2

Employees

Section D

Sub-section D-1
Sub-section D-2

Section E

Sub-section E-1
Sub-section E-2
Sub-section E-3
Sub-section E-4

Section F

Sub-section F-1
Sub-section F-2
Sub-section F-3

I need to be able to search only in Employers or Employees. And the search results must be limited to those indivual landing pages.
Thoughts?
Answer: I was able to resolve the issue by using the Views, not through the search indexes as I initially thought was the path for a solution.
Created a required field for the content-types that would be searched against. Let's call it Section for now, with the values of Employers and Employees. This will be used in the view to filter content by section. (Taxonomy terms can be used for this as well.)
Then created a view page for each section.

In the view, used Content for the row style with Search result highlighting input option, and sorted content by Search: Score (asc).
The real trick for this to work is enabling Search result highlighting input display mode and configuring it with the fields we want to be searched within.
Hope this helps who needs a similar solution in their projects.
Answer: Thee is no out of the box solution available.
Nodes have a "Path" field, but it's a special field at the moment that doesn't load data when requested.
Using the Search API project, you could implement your own code to make the path available at index time, so that you can filter by it.
What's more common is to not have the path be the primary data for this but have reference fields or list fields where you store this information and based on that generate an automated alias (menu still needs to be set up manually). Then you are close to being able to create a view that allows to search and filter by that field.


Why should postgresql.conf not be in the same dir as recovery.conf?

Question: Apparently, I should put postgresql.conf in a separate directory, according to this:
# Note that recovery.conf must be in $PGDATA directory.
# It should NOT be located in the same directory as postgresql.conf

Is there any particular reason? I've seen systems where the two seem to work fine when they're both in the $PGDATA directory.
Answer: This comment is meant to users who have postgresql.conf outside of $PGDATA. For instance Debian-based packages for PostgreSQL install the data directory inside /var/lib/postgresql and the configuration files inside /etc/postgresql/.
With that layout, some users could think of putting recovery.conf in the same directory than postgresql.conf, just because it's a config file too. But it's a mistake, it would be ignored.
To be less ambiguous, the second sentence could be:
# It should NOT be located in the same directory as postgresql.conf,
# unless that directory happens to be $PGDATA

Comment: YES! It certainly should say that, especially since the default configuration has postgresql.conf in $PGDATA


Proving $\sup\left\{ r\in\mathbb{Q}:r^{2}<3\right\}=\sqrt{3}$

Question:
Let $E=\left\{ r\in\mathbb{Q}:r^{2}<3\right\}$.  Prove that $\sup E=\sqrt{3}$.

Since $E$  is bounded from above by $\sqrt{3}$  and is nonempty, $\alpha:=\sup E$  must exist by the Least Upper Bound Principle. Now I am stuck. Suppose $\alpha<\sqrt{3}$. Then what?
Edit: It just hit me.  If $\alpha < \sqrt{3}$ then since the rationals are dense in $\mathbb{R}$, there exists $q\in\mathbb{Q}$ such that $\alpha < q <\sqrt{3}$ and hence $\alpha^2 <q^2 <3$ which contradicts the fact that $\alpha$ is the sup of $E$
Comment: Well, how do you know the rationals are dense in $\Bbb R$? That's a strong result.
Comment: @Peter: Perhaps they either proved that in class or were told to use it freely. I don't image that one would assign such an exercise otherwise (this exercise is trivial compared to proving density of rationals).
Comment: @William But it can be proven given $m/n<\sqrt 3$, there is another $p/q$ dependent on $m/n$ such that $m/n<p/q<\sqrt 3 $
Comment: @Peter: Yup, and using exactly that one proves density of rationals. Notice, I'm not saying that density of $\mathbb{Q}$ is nontrivial, but only that the exercise above follows trivially from density of $\mathbb{Q}$.
Comment: @William Sure. ${}{}$
Comment: What's your definition for real numbers? Different difinitions result in different proofs.
Answer: Let $r\in \bf E$ , $r = \dfrac m n $.
Then we need to prove that there always exists a $\dfrac{p}{q}$ such that
$$ \frac{m}{n}<\frac p q < \sqrt 3$$
By exploting the special properties of $\sqrt 3 $,we can do it:
We start with
$$\eqalign{
  & r < \sqrt 3   \cr
  & r + 1 < \sqrt 3  + 1  \cr
  & \frac{1}{{r + 1}} > \frac{1}{{\sqrt 3  + 1}}  \cr
  & \frac{1}{{r + 1}} > \frac{{\sqrt 3  - 1}}{2}  \cr
  & \frac{{r + 3}}{{r + 1}} > \sqrt 3  \cr} $$
But now we've gotten a number greater than $\sqrt 3 $. So what we'll do is apply the process again, and the relation will be reversed:
$$\frac{{Q + 3}}{{Q + 1}} < \sqrt 3 $$
Letting ${Q = \frac{{r + 3}}{{r + 1}}}$ will give
$$\frac{{2r + 3}}{{r + 2}} < \sqrt 3 $$
All we need to do now is prove that
$$r < \frac{{2r + 3}}{{r + 2}}$$
But since $r+2>0$ we get that
$$\eqalign{
  & {r^2} + 2r < 2r + 3  \cr
  & {r^2} < 3 \cr} $$
which is true by hypothesis. Thus, given any rational $r$, there exists another rational $q$ such that
$$r<q<\sqrt 3$$
where $$q = \frac{{2r + 3}}{{r + 2}}$$
Just to make things clear, I'll add some extra information.
The recursion defined as $r_0=1$ $$r_{n+1}=\frac{2 r_n+3}{r_n +2} $$ converges monotonically (increasing) to $\sqrt 3 $. This in particular means that given any $\epsilon>0$ there is an $r \in \rm E$ such that $$\sqrt 3 -\epsilon < r$$ which means $\sqrt 3 $ is the supremum of the set.
This also plays the role of showing that $3$ is irrational.
Comment: Have you discriminate this case: there exists rational numbers $r_10$?
Comment: @FrankScience I think this shows that no rational number can be the supremum you are looking for - there is always another rational number greater than the one you chose and less that $\sqrt 3$. If $\alpha$ is not rational and less than $\sqrt 3$ then consider $\beta = \sqrt 3 - \alpha$. Choose an integer $N > \beta$ which you can do by "Archimedes Axiom" and consider rationals with denominator $N$. This gives you a rational between $\alpha \text { and } \sqrt 3$, so that $\alpha$ can't be the sup.
Comment: One more step is required namely let $r\notin E$ and $r>0$ be a rational number then $\exists\ q\in \mathbb Q$ such that $\sqrt 3< q< r$. Check that $q=\frac{2r+3}{r+2}$
Comment: @MarkBennet Yes, but I think it is not trivial in Peter's proof. I have mentioned that, the different definitions of real numbers result in different proof, and notice that, Archimedes Axiom implies the original problem directly.
Comment: @MarkBennet For example, $m$ is such a large positive integer that $m>1/\epsilon$, then consider the $n/m$ for all nonnegative integer $n$, and $n_0=\sup\left\{\;n\in \Bbb Z\;\big|\;n/m\leq\sqrt 3\;\right\}$, we have $n_0$ is a nonnegative integer and $|n_0/m-\sqrt 3|\leq1/m<\epsilon$.
Comment: @MarkBennet I think the Archimedes Axiom should be proved by least upbound principle. For example, consider $n_0=\sup\left\{\;n\;\big|\;n\le\alpha\;\right\}$, prove that $n_0\in\Bbb Z$ and show that $n_0+1>\alpha$.
Comment: @FrankScience - You need Archimedes Axiom, or something similar, to  prove this. How else are you going to find a rational number between two real numbers, or show that the rationals are dense in the reals?
Comment: @MarkBennet As I've shown, Achimedes Axiom results from the completeness of real numbers. A definition of real number at [Wikipedia](http://en.wikipedia.org/wiki/Construction_of_the_real_numbers#Synthetic_approach)
Comment: @FrankScience You can show that the recursion obtained, namely $r_{n+1}=\frac{2r_n+3}{r_n+2}$ converges to $\sqrt 3$ (which means there is not such an $\alpha$). This in particular means that given any $\epsilon >0$ there is an $r \in \rm E$ such that $\sqrt 3 - \epsilon < r$, which proves that the supremum is $\sqrt 3$.
Comment: @Kuashik I don't follow. Why do you think that is required?
Comment: @PeterTamaroff I get it. I think $r_{n+1}=(r_n+3/r_n)/2$ might be better. Incidentally, what's the largest speed of convergence when we use $r_{n+1}=(\alpha r_n+\beta)/(\gamma r_n+\delta)$? Is it yours?
Comment: @Peter Tamaroff: I take supremum of a subset of $\mathbb R$ is a least upper bound of that subset.


How to implement pager in custom page template?

Question: in my theme I need a custom front page which displays a filtered set of news and paginated. The news are nodes with content type=news, and every one has a field "is topnews", so that only the freshest topnews is displayed at the top and all other news are displayed (with another layout) below the topnews.
So I created a page--node--9.tpl.php (which corresponds to the "empty" frontpage I created in the drupal backend), and used this code to get the topnews:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition("type","news");
$query->fieldCondition("field_news_typ","value","Topnews","=");
$query->propertyOrderBy("created","DESC");
$query->range(0,1);
$result = $query->execute();

Then I output the topnews with its special HTML and use this code to get all other news:
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition("type","news");
$query->propertyOrderBy("created","DESC");
$result = $query->execute();

In the iterator loop I check the node-id against the topnews-node-id and output regular HTML for the news if they don't match. Now I want to add a pager to the mess so I can paginate the "normal news", but adding a ->pager(3) to the second query before the execute() call does not work and a var_dump(theme("pager")) returns NULL.
So there are two questions:
a) how do I make a pager (bonus points: the end result should be an AJAX pager which loads the HTML for ordinary news!) and
b) how do I move all that logic out of the .tpl.php and instead follow the "proper" drupal way? I imagine that having the "ordinary" and "topnews" HTML in separate .tpl.php files would be helpful in implementing said AJAX paging.
Answer: This can and should almost certainly be done entirely with the Views module (which is/will be in Drupal 8 core!). The filtering of your content by type and the value of the "top news" field can all be done with Views, along with the ajax pager. You can then use the Views attachment display type to attach those news items which do not have the "top news" box checked. You may also want to look into the Nodequeue module for ordering content in more ambiguous ways than just the most recent or whatnot, but you can also use Drupal's "sticky" setting on nodes that you want to keep at the top of the list and highlight, format them differently, etc. Views also allows you to rewrite the output of every item in the results in the UI or using tpl files. Views, my friend. Views.


Mensagem ao final de na.omit

Question: Estou usando o comando na.omit(matrix.work) e ao final aparece a mensagem:
attr(,"na.action")
[1]  3 11
attr(,"class"

Alguém sabe como posso suprimir esta mensagem, pois não quero que ela apareça por estar carregando o conteúdo em uma variável.
Answer: Essa mensagem não é um problema... São apenas atributos que a função coloca na matriz resultante. Uma matriz com esses atributos continuará se comportanto como uma matriz. Basta ignorá-los.
Dito isso, se você ainda quiser excluí-lo, pode fazer o seguinte:
a <- matrix(rep(c(NA, 1:4), each = 20), ncol = 10, byrow = T)
b <- na.omit(a)
attr(b, "na.action") <- NULL
b
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    1    1    1    1    1    1    1    1     1
[2,]    1    1    1    1    1    1    1    1    1     1
[3,]    2    2    2    2    2    2    2    2    2     2
[4,]    2    2    2    2    2    2    2    2    2     2
[5,]    3    3    3    3    3    3    3    3    3     3
[6,]    3    3    3    3    3    3    3    3    3     3
[7,]    4    4    4    4    4    4    4    4    4     4
[8,]    4    4    4    4    4    4    4    4    4     4

Na linha que tem attr(b, "na.action") <- NULL você está atribuindo NULL ao atributo que a função na.omit acrescentou, o que é equivalente a excluí-lo.
Uma forma mais concisa, mas menos intuitiva é fazer:
b <- na.omit(a)[T,T]

Isso resulta em uma matriz sem atributos extras por uma característica da função [, que pode ser encontrada na docuemntação (?"["):

Subsetting (except by an empty index) will drop all attributes except
  names, dim and dimnames.

Mensagem ao final de na.omit


Method of reading next line after a condition is satisfied in python

Question: I have an input .txt file in the format:
1. ##Header1
2. 100    200
3.
4. ##Header2
5. ABCDEFG

I want to read the line ##Header1, and then go to the next line and save it as a variable.
I have seen suggestions to use next() but as the line in the input file is a string (not an iterator), I get an error. Here is my code:
    with open(file_name, 'r') as fin:
        for line in fin:
            if "##Header1" in line:
                contents_of_next_line = next(line)

Comment: You have no function definition in your post.  It's not clear what the function is supposed to do overall.
Answer: Try next(fin) instead of next(line). fin is the iterator, calling next on it will yield you the next line.


Can not get POST data with bootstrap and node

Question: I'm using bootstrap to build a form, but when click the submit button, no POST data sent to my back-end server.
The code of Front is :
    <form class="form-horizontal" id="level_form" method="post" action="" data-confirm="Ready to submit?">

                    <input type="date" id="startDate">

                    <input type="date" id="stopDate">

                <button type="submit" class="btn btn-primary">submit</button>
                <button type="button" class="btn">preview</button>

    </form>

And the backend is :
app.use(express.bodyParser());

app.engine('html', cons.mustache);
app.set('view engine', 'html');
app.set('views', __dirname+'/views');
app.use(express.static(__dirname + '/public'));

app.use(express.basicAuth(function(user, pass){
    return user == 'admin' && pass == 'solid'
}));

app.use(app.router);

app.get('/', function(req, res){
    res.render('index', {});
});

app.get('/new_level', function(req, res){
    res.render('level_editor', {action_url:'/new_level'});
});
app.post('/new_level', function(req, res){
    console.log(req.body);
    res.send(req.body);
});

But all I got is a '{}', where did I do wrong? The html part or the node part?
Answer: In your html action="/new_level" and all your inputs should have name attribute. Check here Node.js/Express form post req.body not working


Smartgwt form's item

Question: I am developing a website using both Smartgwt and GWTP.
When tesing with IE8, I click on some form items which have some button on it, like SelectItem, ColorPickerItem and DateItem, it will lead me to the default page. For example if i am on
    http://127.0.0.1:8888/mypage.html?gwt.codesvr=127.0.0.1:9997#!somepage
, then I click on those items on this page, the address will become
    http://127.0.0.1:8888/mypage.html?gwt.codesvr=127.0.0.1:9997#
But when I use Chrome, then there is no problem.
Could any one tell me what is the problem?
Thanks.
Answer: This sounds like a bug in GWTP - it suggests that they are adding anchors to all  elements anywhere on the page, or adding event handlers to all such elements, including ones rendered by SmartGWT.

Smartgwt form's item


Concatenate some columns in Panda Dataframe?

Question: Trying to figure out how to do this. I have a text file that has data in it, such as the example below. When I read in the file using read_csv, I am left with columns of strings. I am trying to concatenate columns of each row into one column.
There will be more data in other columns that I can't concatenate, so my thinking was that with the for loop, I can change it to not loop through those columns.
.txt file:
Test data 1 1
Test data 2 2 2
Test data 3 3 3 3
Test data

My previous method was to find the lastcol and use that as the maximum, then use a for loop.
df = pd.read_csv(filename, sep='\s+', header=None)
cols = list(df.columns)
lastcol = cols[-1]
n = 0
df['testColumn'] = df[n].map(str)
for n in range (0,lastcol):
   df = df.replace(np.nan, '', regex=True)
   df['testColumn'] = df['testColumn'] + ' ' + df[n+1].map(str)

This works fine when the data in row 1 has the most columns. However, this fails upon entering the second row if the data row 2 has more columns than the row 1, such as in the .txt file example.
I am thinking my issue now is in how I am grabbing the end column. I am somewhat new to Python.
Here is the current output of when a text file has the first row with the most columns:
      0     1  2  3  4            testColumn
0  Test  data  1  1  1  Test data 1 1.0 1.0
1  Test  data  2  2        Test data 2 2.0
2  Test  data  3              Test data 3

Here is the current output error when a text file has the most columns in a different row (using text file example above):
pandas.errors.ParserError: Error tokenizing data. C error: Expected 4 fields in line 2, saw 5

Comment: Not clear what you want to do, can you provide the output? What about `df.fillna('').apply(''.join, axis=0)` (depending on the output you want try `axis=1`)
Comment: Welcome to stack overflow! Can you [edit] to include your expected output so that we can better understand how to help?
Comment: @G.Anderson Will do! Thanks!
Answer: Try:
import pandas as pd
import re

with open(filename) as f:
   df = pd.DataFrame([re.split(r'\s+', l.strip()) for l in f.readlines()])
df.fillna("", inplace=True)

df['testColumn'] = df.apply(lambda x: ' '.join(x), axis=1)

print(df)

# output as a new CSV file
df.to_csv('out.csv', index=False, header=None, sep=',')

The first part handles the variable columns in the data and creates a data frame from a list.
If want to select which columns to concatenate try this:
df['testColumn'] = df[[0,2]].apply(lambda x: ' '.join(x), axis=1)

Output:
      0     1  2  3  4  5         testColumn
0  Test  data  1  1          Test data 1 1
1  Test  data  2  2  2      Test data 2 2 2
2  Test  data  3  3  3  3  Test data 3 3 3 3
3  Test  data                  Test data

Comment: This works well. I do have a question. With this methodology (and changes made), would it be possible to concatenate select columns?
Comment: If want only columns 1 and 3 use `df['testColumn'] = df[[0,2]].apply(lambda x: ' '.join(x), axis=1)`
Answer: If you want the data to be as one column, there is no need to split it in the first place:
df = pd.read_csv(filename, header=None)

Comment: I should have clarified that I can't do this. The .txt file only part of the data I am reading, where there will be more columns that can not be concatenated that I am testing on.


How do fabrics, impermeability, buoyancy, and swimwear length enhance a swimmer's performance?

Question: In 2008, Speedo launched the LZR Racer, a high-tech swimwear.  Since high-tech swimwear were launched, over 130 world records have been broken.
As a result, FINA, the International Swimming Federation, banned full-body length and high-tech swimwear starting in 2010.
The LZR Racer used a "high-technology swimwear fabric composed of woven elastane-nylon and polyurethane." How do fabrics, impermeability, buoyancy, and swimwear length enhance a swimmer's performance?
Answer: Fabrics are used to improve shape retention to reduce vibration, and increase muscle compression to retain muscle shape to reduce fatigue and power loss.
High-tech swimwear transforms a "less than perfect" physique into an ideal physique for swimming. Also, seams in high-tech swimwear are ultrasonically welded rather than stitched, to further promote the streamline effect.
Impermeability reduces friction between water and the fabric, and also reduces drag.
Speedo added polyurethane panels that repelled water. Reducing aerodynamic properties increases a swimmer's speed in the water.
Buoyancy elevates a swimmer higher in the water.
Some swimmers wore two articles of high-tech swimwear to achieve a buoyant effect.
Swimwear length: Full-body length swimwear covers more surface area of the body. This works hand-in-hand with fabrics to achieve the compressive, impermeable, and buoyant benefits of high-tech swimwear.


Spark RDD functions on CSV file

Question: I am trying to load the csv file through SparkContext and after loading i need to perform any RDD operations on required columns of CSV file.
I was able to read csv file and fetch the required columns from JavaRDD. Now i need to perform any RDD operations on these columns.
This is what i have tried so far..
JavaRDD<String> diskfile = sc.textFile("/Users/hadoop/Downloads/Data_1.csv");

  JavaRDD<Object> newRDD = diskfile.cache().map(lines -> Arrays.asList(new String[]{
          lines.split(",")[0],
          lines.split(",")[1]
        }

          ));
 System.out.println(newRDD.collect());

newRDD.collect() prints 0th column and 1st column of csv data. Now i need to perform any RDD operations on newRDD.
Thanks in advance.
Answer: If you wanna get started with Spark RDD transformations then you can go to the following links :
RDD-Basic-Examples
RDD API Examples
Word Count Example in java using the flatMap, mapToPair, reduceByKey transformations :
JavaRDD<String> textFile = sc.textFile("hdfs://...");
JavaRDD<String> words = textFile.flatMap(new FlatMapFunction<String, String>() {
  public Iterable<String> call(String s) { return Arrays.asList(s.split(" ")); }
});
JavaPairRDD<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() {
  public Tuple2<String, Integer> call(String s) { return new Tuple2<String, Integer>(s, 1); }
});
JavaPairRDD<String, Integer> counts = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
  public Integer call(Integer a, Integer b) { return a + b; }
});
counts.saveAsTextFile("hdfs://...");

Comment: Thanks for response, i know about RDD operations. here my requirement is to apply rdd operations on two columns of csv data.
Comment: wt operation you are looking for ?
Comment: i need to return column2 value with respective to max value of column1.
Comment: wt u need to apply is `sortByKey`.  you can use rdd.sortByKey(), it will sort the rdd based on the key
Comment: but my input RDD is of type Object, as per my knowledge soryByKey is only aplicable for RDD. sorry if iam wrong
Comment: yes, in the map function u have written, create a map or touple2, so that u cn use `sortByKey`. U need to update your map function which would return rdd of key,value pair
Comment: can you share your idea how to return RDD from RDD?

Spark RDD functions on CSV file


Calculating multivariable limit

Question: $$\lim_{(x,y) \to (0,0)} \frac{x^2y}{x^3 + y}$$
I tried the following, but im not sure if this is allowed:
Let $$t = x^3+y$$ $$(x,y)\to (0,0)$$  $$t\to 0$$ $$y=t-x^3$$
Now we will calculate the limit: $$\lim_{(x,t) \to (0,0)}x^2-\frac{x^5}{t}$$
Lets look at the path $t=x^6$ $$\lim_{(x,t) \to (0,0)}x^2-\frac{x^5}{x^6}=-\infty$$
Now lets look at the path $t=x^5$ $$\lim_{(x,t) \to (0,0)}x^2-\frac{x^5}{x^5}=-1$$
We found 2 different limits hence the limit does not exist.
Is this correct? or am I doing something wrong? thanks.
Answer: The function is not continuous at (0,0).  Another way to see this is to take the limit along $y = 0 $ and $y = x^6 - x^3$.  Your approach is correct.
Comment: I think both are $0$...
Answer: In multivariable calculus the approach to show that a limit does not exist is exactly the approach you used. Although you used an extreme hard path, in my opinion, you could try to use some simple cases like:
$$ y = 0 $$
$$ x = 0 $$
$$ y = x^2 $$
$$ y = -x $$
$$ y = x $$
If, in these five cases, it converges to the same limit value, it probably - but not necessarily - has a well defined limit. Otherwise it doesn't have one.
As suggested by @mic, this technique only proves that a limit doesn't exist, but cannot prove that it exists. It just suggests a guess for its value. A good way to prove would be to use the delta, epsilon definition of limits.
Comment: This technique leads to a conjecture, hardly a proof.
Comment: If this shows that a limit doesn't converge to a value it doesn't have one, otherwise you could try to use more advanced techniques. It doesn't proves that a limit doesn't exist by just using those five assumptions.
Comment: I stand corrected. This technique can show whether a limit does not exist or can suggest a guess about its value (but does not prove whether such guess is correct).
Comment: What about now @mic?
Comment: Sounds better to me.

Calculating multivariable limit


Making "Read More" post link w/ Markdown [POSTACH.IO]

Question: This is my first time using Markdown, and it seems pretty simple. I am using it on an opinion blog I have for Postach.io
I am used to Tumblr's WYSIWYG, with the "READ MORE" tag option; however, postach.io only allows READ MORE by limiting characters. How can I use Markdown to make a READ MORE tag, directing it to the permalink of my post?
--> I use the Evernote Desktop program to create my blog entries, and have the markdown option selected online.
Answer: If you still need an answer - and I needed one, which is how I ended up at this page in the first place - Use [[MORE]] in the spot where you want the break to happen. It's a tumblr-specific thing, and it works in both HTML and Markdown mode.
Example:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. [[MORE]] Pellentesque quis lacinia orci, vel fringilla quam. In vitae tortor vitae purus volutpat consequat. Pellentesque sagittis libero vitae hendrerit dignissim. Cras laoreet.

Displays on people's dashboards as:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Read More →

With the "Read More" linking to the full post, as it would if you had added it in the HTML or WYSIWYG editor:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis lacinia orci, vel fringilla quam. In vitae tortor vitae purus volutpat consequat. Pellentesque sagittis libero vitae hendrerit dignissim. Cras laoreet.
Answer: Since postach.io doesn't support it, you can't do it. Well, not without quite a lot of work anyway.
You could create two posts, one with full content and the other with the short version. Post the full version first, but hidden (assuming there is someway to do this). Then create a normal markdown link in the short version to the long version and post the short version normally.
Comment: This was my first idea, but after some research, to have anything published, it needs to be tagged with "published"... Then it would still appear on the blog's homepage and there would be duplicates. Thank you though.


Get current rowIndex of table in jQuery

Question: My table cell gets highlighted when clicked. I need to find the rowIndex of highlighted cell.
I tried doing like this
$(".ui-state-highlight").index(); // Results to 0

I tried this too...
$('td').click(function(){

    var row_index = $(this).parent().index('tr');

    var col_index = $(this).index('tr:eq('+row_index+') td');

    alert('Row # '+(row_index)+' Column # '+(col_index));

});
// Results : Row # -1 Column # -1

I went to through this post and tried the first answer, still couldn't get the result.
Answer: Try this,
$('td').click(function(){
   var row_index = $(this).parent().index();
   var col_index = $(this).index();
});

If you need the index of table contain td then you can change it to
var row_index = $(this).parent('table').index();

Comment: The cell get the class (.ui-state-highlight) so according to your ans i should use $('.ui-state-highlight').parent().index(); .It returns 2 where the highlighted cell is in 4 row considering 0 based.
Comment: You need to use this, If you want the row index of td then $(this).parent().index(); and if you need the index of table contain td then you can change it to $(this).parent('table').index();
Answer: Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:
$('td').click(function(){
   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();
});

Answer:

$(this).closest("TR").index()

This one is also useful in dynamics rendering.

Get current rowIndex of table in jQuery