SSH Public Key Authentication Fails Mac OSX

Question: I am trying to get a coworkers MacBook Air running on Public Key Authentication and even after generating a new SSH key I haven't been able to get it to run like I have mine. Double checked file permissions, added her to all of the proper groups on the server. Configured the server to accept public keys etc. I have copied her id_dsa.pub exactly to the ~/.ssh/authorized_keys file.
EDIT:
I have ran /usr/bin/ssh-add -K which did not work either.
$ ssh -vvv yielded the following debugging:
macbookname:.ssh user$ ssh -vvv user@domain
OpenSSH_5.6p1, OpenSSL 0.9.8r 8 Feb 2011
debug1: Reading configuration data /etc/ssh_config
debug1: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to apistudyabroad.com [126.96.36.199] port 22.
debug1: Connection established.
debug3: Not a RSA1 key file /Users/user/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug2: key_type_from_name: unknown key type 'Proc-Type:'
debug3: key_read: missing keytype
debug2: key_type_from_name: unknown key type 'DEK-Info:'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /Users/user/.ssh/id_rsa type 1
debug1: identity file /Users/user/.ssh/id_rsa-cert type -1
debug3: Not a RSA1 key file /Users/user/.ssh/id_dsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /Users/user/.ssh/id_dsa type 2
debug1: identity file /Users/user/.ssh/id_dsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.8p1-hpn13v10
debug1: match: OpenSSH_5.8p1-hpn13v10 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.6
debug2: fd 3 setting O_NONBLOCK
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: firstname.lastname@example.com,firstname.lastname@example.com,email@example.com,firstname.lastname@example.com,ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,firstname.lastname@example.com
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,firstname.lastname@example.com
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,firstname.lastname@example.com,hmac-ripemd160,firstname.lastname@example.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,firstname.lastname@example.com,hmac-ripemd160,firstname.lastname@example.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,email@example.com,zlib
debug2: kex_parse_kexinit: none,email@example.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,firstname.lastname@example.com
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,firstname.lastname@example.com
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,email@example.com,hmac-ripemd160,email@example.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,email@example.com,hmac-ripemd160,email@example.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,firstname.lastname@example.com
debug2: kex_parse_kexinit: none,email@example.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 122/256
debug2: bits set: 506/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug3: check_host_in_hostfile: host apistudyabroad.com filename /Users/user/.ssh/known_hosts
debug3: check_host_in_hostfile: host apistudyabroad.com filename /Users/user/.ssh/known_hosts
debug3: check_host_in_hostfile: match line 3
debug3: check_host_in_hostfile: host 18.104.22.168 filename /Users/user/.ssh/known_hosts
debug3: check_host_in_hostfile: host 220.127.116.11 filename /Users/user/.ssh/known_hosts
debug3: check_host_in_hostfile: match line 3
debug1: Host 'apistudyabroad.com' is known and matches the RSA host key.
debug1: Found key in /Users/user/.ssh/known_hosts:3
debug2: bits set: 516/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /Users/user/.ssh/id_dsa (0x7f951bc24750)
debug2: key: /Users/user/.ssh/id_rsa (0x7f951bc24200)
debug1: Authentications that can continue: publickey,keyboard-interactive,hostbased
debug3: start over, passed a different list publickey,keyboard-interactive,hostbased
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering DSA public key: /Users/user/.ssh/id_dsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,keyboard-interactive,hostbased
debug1: Offering RSA public key: /Users/user/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,keyboard-interactive,hostbased
debug2: we did not send a packet, disable method
debug3: authmethod_lookup keyboard-interactive
debug3: remaining preferred: password
debug3: authmethod_is_enabled keyboard-interactive
debug1: Next authentication method: keyboard-interactive
debug2: userauth_kbdint
debug2: we sent a keyboard-interactive packet, wait for reply
debug2: input_userauth_info_req
debug2: input_userauth_info_req: num_prompts 1
Password:

Am I missing something?
Answer: Here are some questions to rule out simple causes?

Are you using the correct user ID when connecting to the Air?
Are you sure that the authorized_keys file is mode 600, the .ssh directory is mode 700, and that the home directory is not writable by anyone other than the owner?
The server should already have been configured to accept key-based authentication.  If you had to change something, what was it?
Have you looked in the system log (/var/log/system.log) to see if there are any relevant error messages?

If nothing on the above list helps out, here's a quick way to diagnose problems:

Stop the ssh server.  There are various ways to do this, but the easiest is to uncheck the "remote login" checkbox in the "Sharing" control panel.
As root, start the ssh server on the command line with the -d flag.  This will accept one connection and print out lots of debugging information:
$ sudo /usr/sbin/sshd -d

Review the debugging information for any useful error messages.
Don't forget to restart the ssh server.

If you don't see anything helpful, post the logs here.
Answer: Run ssh -vvv on the client for extended output and check the server logs. It is a common mistake to not make the key mode 0600 and owned by the user. Ssh will refuse authentication if the private key is readable by others or if authorized_keys is writable by others.
Comment: The files are already 0600.
Comment: I have included the output above.
Answer: Try running the ssh-add -K command.

image credit
Answer: You could try using Userify to distribute the keys to ensure permissions are set correctly on the remote host. (Also Userify has a good howto for Mac with usage tips).


Do I need SSL certificate for my website to get info for my iphone app?

Question: I am working on iPhone app with NSURLConnection api. I created Login/Signup screens and just realized something missing with my website server that I didn't have SSL certificate yet for secure personal info.
I am wondering if you ever need to have SSL certificate for your website server for your iPhone app to get HTTP request for your login/signup. My app doesn't have any payment info just only username/email/password info. I just want to make sure all those infos will be stored in a secure way. Please let me know if I need SSL certificate or not. Any suggestion appreciated. Thanks!
Comment: If you don't secure and it gets sent plaintext, your accounts could be hijacked and worse, if the user uses the same password for things like Facebook, you could have serious egg on your face.
Answer: No you don't need to, but it is recommended as otherwise, the credentials will be sent in cleartext.
Answer: You mix talk of storage and transmission in the same sentence but they are separate things and the SSL has got nothing to do with storage of items on the iOS device.
If you transmit the information using HTTP it will be unencrypted and anybody can read it.
In order to encrypt it you have to send it using HTTPS, which requires a certificate.
This will only encrypt the data, it won't prove to your device that the server is who it says it is. Even if you are using HTTPS/certifcates there is no guarantee that the server is who he says he is UNLESS you additionally validate that certificate in your handset code. If you want good reference material for this see the book "iOS 5 Programming Pushing The Limits".
As for secure storage of data on the client that's an entirely different matter (the quick and easy answer that everybody says is use keychains, however if you're serious about security I recommend reading the book "Hacking and Securing iOS Applications" to realize just how insecure data on the iPhone can be.).


Trying to get records from joined tables in wp

Question: I am trying to join my two tables here. I searched how it's done in WP and came up with the following code, but it doesn't retrieve records from my tables. What is wrong here?
<code> $tbl_name  = $wpdb->prefix."member_deposit";
 $table_name  = $wpdb->prefix."users";

 $results = $wpdb->get_results("select * from  $tbl_name  INNER JOIN $table_name ON users.ID = member_deposit.ID   WHERE member_deposit.approve = 'unapprove'");
</code>
Answer: Use below code:
<code>$tbl_name  = $wpdb->prefix."member_deposit";
$table_name  = $wpdb->prefix."users";

$results = $wpdb->get_results("select * from  $tbl_name  INNER JOIN $table_name
ON $table_name.ID = member_deposit.ID   WHERE $tbl_name.approve =
'unapprove'");
</code>


Round float to 2 digits after dot in python

Question: I'm using this code:
f = 0.3223322
float('%.2f' % (f))

Is there more pythonic, less verbose method without 2 castings?
Using round is discouraging by the following note from the documentation

The behavior of round() for floats can be surprising: for example,
  round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a
  bug: it's a result of the fact that most decimal fractions can't be
  represented exactly as a float. See Floating Point Arithmetic: Issues
  and Limitations for more information.
Comment: Note that `float('%.2f' % f)` has exactly the same issue as `round()`. That's because, as the documentation says, it's a limitation of the way floating points work on computers. I wouldn't worry about it in most situations. In case it does matter, I think it's better to use the `decimal` module, or the `fractions` module, or some arbitary precision library, depending on the exact use case.
Comment: What are you trying to round for?
Answer: round(number[, ndigits]):
>>> round(0.3223322, 2)
0.32

Note that you'll probably still want to use a certain precision of string formatting when producing output due to floating point imprecision.
Depending on what you're trying to achieve, it might be appropriate to use the Decimal type:
>>> from decimal import Decimal
>>> round(Decimal(0.3223322), 2)
Decimal('0.32')

which does its math in (surprise!) decimal instead of binary and therefore doesn't suffer any issues with decimal rounding (except initially if you're trying to create it from a float).
Answer: This is not as nice, but I'm always a fan of:
f=float(int(100*f))/100

Far from the best way to do it, but it's one I use often.
Answer: Whats wrong with good old, built in round()?
Use it like so:
round(input, digits)

Example output:
>>> f = 0.3223322
>>> round(f, 2)
0.32

Comment: In round function if your number after digits upper than 5 return number that greater than of you excepted number
for example:
round(3.248) => 3.25
Answer: I'd go with round() but if you don't like its behavior you can always write your own round() so, for the sake of completness:
def custom_round(number, ndigits=2):
    return int(number * 10 ** ndigits) / 10.0 ** ndigits if ndigits else int(number)

Keep in mind that this round, unlike the builtin round() rounds down, not up.
Answer: You can use Decimal with quantize and rounding. ROUND_HALF_UP is a mathematical rounding.
from decimal import Decimal, ROUND_HALF_UP

>>> Decimal('123.527').quantize(Decimal('.01'), rounding=ROUND_HALF_UP)
Decimal('123.53')

>>> Decimal('123.525').quantize(Decimal('.01'), rounding=ROUND_HALF_UP)
Decimal('123.53')


Angular 2 so many private functions! - Unit test them? Make them public?

Question: I'm finding that the largest majority of my functions in my Angular 2 app are private. for example, look at this component (my largest component - it is a form - so it has a lot of controls which are child components)
<code>import {
    Component,
    ViewChild,
    ElementRef,
    EventEmitter,
    Output,
    OnInit
} from '@angular/core';
import {
    FormGroup,
    FormBuilder,
    Validators,
    ControlValueAccessor,
    FormControl,
    AbstractControl,
    ReactiveFormsModule
} from '@angular/forms';
import { ResultService } from '../../../services/result.service';
import { Result, FindRequest } from '../../../models/all-models';
import { HighlightDirective } from '../../../directives/highlight.directive';
import { DistanceUnitsComponent } from './distance-units.component';
import { MultiselectComponent } from
    '../../../shared/subcomponents/multiselect-find-category.component';
import { MultiselectFindMealTypeComponent } from
    '../../../shared/subcomponents/multiselect-find-meal-type.component';
import { NumberPickerComponent } from './number-picker.component';
import { InputComponent } from '../../../shared/subcomponents/input.component';
import { AreaComponent } from
    '../../../shared/subcomponents/area-picker.component';

@Component({
    selector: 'find-form',
    templateUrl: 'app/find-page/subcomponents/find-page/find-form.component.html',
    styleUrls: ['app/find-page/subcomponents/find-page/find-form.component.css'],
    providers: [ResultService]
})

export class FindFormComponent implements OnInit {
    @ViewChild('multiselectFindCategory')
    private _multiselectFindCategory: MultiselectComponent;
    @ViewChild('multiselectFindMealType')
    private _multiselectFindMealType: MultiselectFindMealTypeComponent;
    @ViewChild('distanceUnits') private _distanceUnits: DistanceUnitsComponent;
    @ViewChild('numberPicker') private _numberPicker: NumberPickerComponent;
    @ViewChild('areaInput') private _areaInput: AreaComponent;
    @ViewChild('keywordsInput') private _keywordsInput: InputComponent;
    @Output() private _onResultsRecieved:
    EventEmitter<Object> = new EventEmitter<Object>();
    @Output() private _onSubmitted: EventEmitter<boolean> =
    new EventEmitter<boolean>();

    private _categoryError: string = 'hidden';
    private _mealTypeError: string = 'hidden';
    private _areaError: string = 'hidden';

    private _findForm: FormGroup;
    private _submitted: boolean = false;
    private _findRequest: FindRequest;

    private _displayMealCategories: boolean = false;
    private _mealSelected: boolean = false;
    private _place: google.maps.Place;

    constructor(private _resultService: ResultService,
                    private _formBuilder: FormBuilder) {}

    ngOnInit() {
        this._findForm = this._formBuilder.group({
            categories: [null, Validators.required],
            mealTypes: [[], this._mealTypesValidator()],
            location: null,
            distanceNumber: null,
            distanceUnit: 'kilometers',
            keywords: null,
        });
    }

    private _mealTypesValidator = () => {
        return (control: FormControl) => {
            var mealTypes = control.value;
            if (mealTypes) {
                if (mealTypes.length < 1 && this._mealSelected) {
                    return {
                        mealTypesValid: { valid: false }
                    };
                }
            }
            return null;
        };
    };

    private _setAreaErrorVisibility(): void {
        if (this._areaInput.areaInput.nativeElement.value) {
            if (!this._areaInput.address) {
                this._areaError = 'visible';
            } else {
                this._areaError = 'hidden';
            }
        } else {
            this._areaError = 'hidden';
            this._findForm.get("location").setValue(null);
        }
    }

    private _onCategoriesChanged(): void {
        this._findForm.get('categories').markAsDirty();
        this._mealSelected = this._multiselectFindCategory.mealSelected;
        this._findForm.controls['mealTypes'].updateValueAndValidity();
        if (!this._mealSelected) {
            this._mealTypeError = 'hidden';
            this._findForm.get('mealTypes').setValue([]);
        }

        if (this._multiselectFindCategory.selectedCategories.length > 0) {
            this._findForm.get('categories').setValue(
                this._multiselectFindCategory.selectedCategories
            );
        } else {
            this._findForm.get('categories').setValue(null);
        }
    }

    private _onMealTypesChanged(): void {
        this._findForm.get('mealTypes').markAsDirty();
        if (this._multiselectFindMealType.selectedCategories.length > 0) {
            this._findForm.get('mealTypes').setValue(
                this._multiselectFindMealType.selectedCategories
            );
        } else {
            this._findForm.get('mealTypes').setValue([]);
        }
    }

    private _onAreaChanged(areaEntered: any): void {
        this._setStateOfDistanceControls(areaEntered.areaEntered);
        this._areaError = "hidden";
        if (areaEntered.place) {
            this._findForm.get("location").setValue({
                lat: areaEntered.place.geometry.location.lat(),
                lng: areaEntered.place.geometry.location.lng()
            })
        }
    }

    private _onDistanceUnitsChanged(distanceUnit: string): void {
        this._findForm.get("distanceUnit").setValue(distanceUnit);
    }

    private _onDistanceNumberChanged(distanceNumber: number): void {
        this._findForm.get("distanceNumber").setValue(distanceNumber);
    }

    private _setStateOfDistanceControls(areaEntered: any): void {
        if (areaEntered) {
            this._distanceUnits.isEnabled = true;
            this._numberPicker.isEnabled = true;
        } else {
            this._distanceUnits.isEnabled = false;
            this._numberPicker.isEnabled = false;
        }
        this._distanceUnits.imagePath = this._distanceUnits.imagePath;
    }

    private _getResults(form: FormGroup): void {
        var results: Result[] = [];
        results = this._resultService.getResults();
        if (results) {
            this._onResultsRecieved.emit({
                recieved: true,
                results: results,
                location: this._findForm.get("location").value
            });
        }
    }

    private _onSubmit(model: any, isValid: boolean): void {
        this._submitted = true;
        console.log(model, isValid);
        this._setAreaErrorVisibility();
        if (isValid && this._areaError === "hidden") {
            this._onSubmitted.emit(true);
            this._getResults(this._findForm);
        }
    }
}
</code>
I'm trying to be best practice here. So I have no public anythings...This seems to me like something that comes with Angular 2, because in most of my non-angular apps, I need more public things. Is my code just super loosely coupled, since no other components need to access it? I can't figure out if it is good..
But I need to unit test it and usually you don't unit test anything that's private so I'm pretty confused. I have a lot of logic that obviously should be tested.
Am I making too many things private? Or is it good practice having them private? And should I just unit test all the private functions?
Answer: I would suggest you to make everything public / do not add any prefix  that is being exposed to your template html or of course other components. This is also the way we do it in our company and the way it is done in the official Angular2 guides.
This way you automatically test your private functions since they should be called somewhere in your public methods.
You can also create UI-Tests with things like Protractor and Selenium to cover lots of scenarios
Comment: Thanks. After doing some research into what you are saying I found it to be true. For one thing, it's best to release production code with AoT compilation, and in AoT compilation the HTML template cannot access private variables of its associated component. references: [SO answer](http://stackoverflow.com/a/39000046/3935156), [app demonstrating](https://github.com/devoto13/angular2-private-members-example), [SO answer](http://stackoverflow.com/a/39379451/3935156),
[angular 2 AoT docs](https://angular.io/docs/ts/latest/cookbook/aot-compiler.html)


Lipschitz and Continuity. Proof assistance request.

Question: I was hoping to get some assistance with my proof. The question asks:

Define $g: \ell_2 \rightarrow \mathbb{R}$ by $g(x)=\sum_{n=1}^{\infty} \frac{x_n}n$. Is g continuous?

I have a feeling that if I can show that this is Lipschitz then the function is continuous. Here is what I have so far:

Let $x\in \ell_2$ then $g(x)=\sum_{n=1}^{\infty} \frac{x_n}n$. But because $x\in \ell_2$ I know that $[ \sum_{k=1}^{\infty}(x_k)^2]^\frac{1}2<\infty$ . And so $\sum\frac{x_n}n<C[ \sum_{k=1}^{\infty}(x_k)^2]^\frac{1}2<\infty$. Take $C=n^2$ then we have that  $\sum\frac{x_n}n<n^2[ \sum_{k=1}^{\infty}(x_k)^2]^\frac{1}2$ proving that g(x) is continuous.

I don't know about my choice of c. It seemed to make sense because because of how g(x) was defined. So $x_1+\frac{x_2}2 + ...<n^2(x_1^2+x_2^2+...)^\frac{1}2$. The problem I'm having is that I don't know what n actually is!! The sum goes to infinity!
Answer: $g$ is linear so it suffices to consider $x_0=0$. Then, by Cauchy-Schwarz,
$\vert g(x)\vert=\vert \sum_{n=1}^{\infty} \frac{x_n}n\vert \le \left \| x \right \|_{2}\sqrt{\sum_{n=1}^{\infty}\frac{1}{n^{2}}}\to 0$ as $\left \| x \right \|_{2}\to 0$.
Answer: Let $y$ be the sequence $(1/n).$ Then $g(x) = \langle x,y \rangle, x \in l^2.$ Any map of this form is a continuous linear functional on $l^2.$
Comment: oh I think this makes sense and I like it more. If y is (1/n) then this is just the dot product between two vectors.


Why aren't the lines in taxicab geometry the geodesics of the $L^1$ metric?

Question: This page claims that the proper lines for taxicab geometry should be the same lines as for Euclidean geometry (with the $L^2$ norm on $\mathbb{R}^2$ instead of the $L^1$ norm for taxicab geometry).

Lines in the Taxicab Plane look like lines in the Euclidean plane...

The same claim also appears to be implicit in the Wikipedia page for taxicab geometry, on this webpage, on this one, and also in the book by Millman and Parker, Geometry: A Metric Approach with Models. All of the sources claim as a result that taxicab satisfies all of the same axioms as Euclidean geometry except for the SAS postulate.
Question: Isn't this a very bad, artificial, and unnatural definition of lines for taxicab geometry?
$\mathbb{R}^2$ with the metric induced by the $L^1$ norm is a length space, according to Exercise 11 here, so the lengths of its geodesics do correspond to the distance between points -- so why shouldn't the "lines" in taxicab geometry be the geodesics with respect to the metric induced by the $L^1$ norm?
If we want to study taxicab geometry, and not Euclidean geometry, shouldn't we only study structures which arise naturally from the geometry's definition, rather than definitions of angle, line, and triangle which are unnaturally "imported" from Euclidean geometry unchanged?
Motivation: The answers to this question will allow me to answer my previous question.
In particular, because of the choice of lines for taxicab geometry, even though it is a length space, this is not a case where $d(A,B)+d(B,C) = d(A,C)$ implies that $A,B,C$ are collinear (although it would be if we chose the lines to be the geodesics of the length space). Thus, in order to define a notion of betweenness, we need to say that $B$ is between $A$ and $C$ if and only if (1) $A,B,C$ are collinear, and (2) $d(A,B) + d(B,C) = d(A,C)$. With a more natural definition of line, like that in Euclidean space, the first condition would be redundant, and the notion of betweenness more intimately and naturally related with our choice of metric.
Answer: Geodesics in the Taxicab plane are not unique. A trivial example of this is given by the points $(0, 0)$ and $(1, 1)$ and the curves formed by going from $(0, 0)$ to $(0, 1)$ then $(1, 1)$ and the other as going from $(0, 0)$ to $(1, 0)$ then $(1, 1)$. The two segments forming the curves are easily seen to both have length 1, and the sum total of those lengths is then 2, so these curves both have length 2. But the distance between $(0, 0)$ and $(1, 1)$ is $|1 - 0| + |1 - 0| = 2$ so both are geodesics. In general, any "stair-step" which always moves parallel to either the $x$- or $y$-axes with no backtracking is a geodesic as can be seen by translating its component segments to match these simpler geodesics. Such a path is a continuous-space version of a Dyck path as described here:
http://mathworld.wolfram.com/DyckPath.html
Thus if we define a line as a geodesic it is subject to a great deal of ambiguity, in particular there are $\beth_1$ geodesics between any two points (it can't be more since geodesics must be continuous). In particular, there would be tremendous ambiguity in the "betweenness" relation as you define it -- I'd believe that in fact any point lying in the rectangle with points $A$ and $C$ would end up as being "between" in this definition, in the sense that "there would exist a line (geodesic) from $A$ to $C$ that passes through the given point".
Yup, it would: Let $A = (x_A, y_A)$, $C = (x_C, y-C)$, and $B = (x_B, y_B)$ with $x_A < x_B < x_C$ and $y_A < y_B < y_C$. Then
$$d(A, B) = |x_B - x_A| + |y_B - y_A|$$
$$d(B, C) = |x_C - x_B| + |y_C - y_B|$$
so
$$
\begin{align}
d(A, B) + d(B, C) &= |x_B - x_A| + |y_B - y_A| + |x_C - x_B| + |y_C - y_B|\\
&= (x_B - x_A) + (y_B - y_A) + (x_C - x_B) + (y_C - y_B)\\
&= x_B - x_A + y_B - y_A + x_C - x_B + y_C - y_B\\
&= x_C - x_A + y_C - y_A\\
&= (x_C - x_A) + (y_C - y_A)\\
&= |x_C - x_A| + |y_C - y_A|\\
&= d(A, C)
\end{align}
$$
So yeah, betweenness this way works terribly. Unless perhaps you want to argue that Taxicab geometry should be a "geometry of solid rectangles" ... but then how is it any different from Euclidean geometry of rectangles I wonder?
(FWIW the midset of Taxicab geometry, that is, the "perpendicular bisector" is FREAKY!!! Scared and disturbed me when I first saw it! I can still feel that fweeky tingley little heebiejeebies feeling a little coming on thinking about it reading right now I'm also getting that with what I just proved above, there is something conceptually horrifying about the idea that my brain makes out that this is like a line that is like, eeeevshz, infinitely swollen or something...)
So we have to narrow things down. It turns out though that Euclidean lines are also a geodesic. The most general definition of arc length of a curve to a metric space $M$ given as $C: [0, 1] \rightarrow M$ is
$$L = \sup \sum_{i=1}^{N} d(C(t_{i+1}), C(t_i))$$
where the supremum is over all partitions $0 = t_1 < t_2 < \cdots < t_N = 1$ of $[0, 1]$. So let $C(t) = (t, kt)$ be a Euclidean line in Taxicab space that is not vertical (vertical can be dispensed with a change of coordinates). Then $d(C(t_{i+1}), C(t_i)) = |t_{i+1} - t_i| + k|t_{i+1} - t_i| = t_{i+1} - t_i + k(t_{i+1} - t_i) = (1 + k)(t_{i+1} - t_i)$ and
$$
\begin{align}
L &= \sup \sum_{i=1}^{N} (1 + k) (t_{i+1} - t_i)\\
&= \sup (1 + k) \sum_{i=1}^{N} t_{i+1} - t_i\\
&= \sup (1 + k) (1)\\
&= \sup (1 + k)\\
&= 1 + k
\end{align}
$$
which is easily seen to be the distance between the start and end points. Note that we used telescoping sum in the above. This can be visualized as the "fallacious" method used to get "$\pi = 4$" in the following answer:
The staircase paradox, or why $\pi\ne4$
This method is correct for Taxicab geometry, and the image correctly shows that the ratio of the circumference of a Euclidean circle to its diameter in taxicab geometry is 4.
Thus, to get a sensible geometry, we pick the Euclidean line as the choice geodesic for the taxicab system.
Comment: Thank you again so much for your answer! I am just putting this here for (my) future reference, to note that the non-uniqueness issue even holds for _all_ p-norms with $p\not=2$, not just $p=1$, so the issue you raise is a concern even more generally than how I scoped my question: https://math.stackexchange.com/questions/641368/characterization-of-uniquely-geodesic-normed-vector-spaces
Answer: If one considers general $L^p$ norms where the distance between two points, $\mathbf{x}$ and $\mathbf{y}$, is defined by
$$ d(\mathbf{x},\mathbf{y}) = \left(\sum_{i}\left| x_i - y_i\right|^p\right)^{1/p}, $$
one can show that for all $p>1$, the geodesics are straight, i.e. Euclidean, lines.
The taxicab metric is the $L^p$ metric with $p=1$. Since all the $L^p$ metrics with $p>1$ have straight lines as geodesics, and, although there are no unique geodesics in taxicab geometry, straight lines do give the shortest distance in the taxicab metric, one could make the argument that straight lines are the natural geodesics for the taxicab geometry that follow from its metric. At least if taxicab geometry is seen as a limiting case of case of $L^p$ geometries with $p>1$.
In order to show that the geodesics for $L^p$ metrics are straight lines, we need to use the calculus of variations. Let $\mathbf{x}(t)=(x_1(t),..., x_n(t))$ be a parametrization of a curve in $\mathbb{R}^n$ . First we need to calculate the distance for two points infinitesimally close on the path $\mathbf{x}(t)$
$$d(\mathbf{x}(t+dt),\mathbf{x}(t)) = \left(\sum_{i}\left| x_i(t+dt) - x_i(t)\right|^p\right)^{1/p}
= \left(\sum_{i}\left| x_i+\frac{dx}{dt} dt- x_i\right|^p\right)^{1/p}
=\left(\sum_{i}\left| \frac{dx}{dt}\right|^p \right)^{1/p}dt.$$
Now let's define the function
$$f(\mathbf{x},\dot{\mathbf{x}}) \equiv \left(\sum_{i}\left|\dot{x}_i\right|^p \right)^{1/p}$$
where $\dot{x_i}=\frac{dx_i(t)}{dt}$. We now need to minimize the integral
$$\int f\left(\mathbf{x}(t),\dot{\mathbf{x}}(t)\right)dt = \int \left(\sum_{i}\left|\dot{x}_i\right|^p \right)^{1/p}dt.$$
This can be done via the Euler–Lagrange equations:
$$\frac{\partial f}{\partial x_i} - \frac{d}{dt}\left(\frac{\partial f}{\partial \dot{x_i}}\right)=0.$$
For our problem, the Euler–Lagrange equations give
$$0-\frac{d}{dt}\left(\dot{x}_i |\dot{x}_i|^{p-2}\left(\sum_{j}\left| \dot{x}_j\right|\right)^{1/p-1}\right)=0.$$
Integrating these equations with respect to $t$, and dividing pairs of them gives
$$ \frac{a_i}{a_j}=\frac{\dot{x}_i}{\dot{x}_j} \left|\frac{\dot{x}_i}{\dot{x}_j} \right|^{p-2}$$
where the $a_i$ are integration constants. There are two cases to check, depending on the sign of $\frac{\dot{x}_i}{\dot{x}_j}$, but it is pretty easy to see that in both cases the equations reduce to
$$\dot{x}_j=\left(\frac{a_i}{a_j}\right)^\frac{1}{p-1}\dot{x}_i$$
(maybe up to a minus sign). These equations can be immediately integrated, and the results are lines. The only issue is when $p=1$, where the equations becomes singular.


Cannot use my own TypeScript library in JavaScript

Question: I've been banging my head against the wall with a seemingly simple task. I would appreciate any insights on this.
I'm writing a private library in TypeScript to be used in both TypeScript and JavaScript projects in our company.
The library works great but I cannot seem to be able to import it in JavaScript.
Library in TS
package.json
{
  "name": "rr-comm-bus-js",
  "version": "0.3.0",
  "description": "",
  "main": "lib/src/index.js",
  "types": "lib/src/index.d.ts",
  "scripts": {
    "dev": "ts-node-dev --respawn src/dev/dev.ts",
    "build": "rm -rf lib && tsc"
  },
  "keywords": [],
  "dependencies": {
    "redis": "^3.1.2"
  },
  "devDependencies": {
    "@types/node": "^16.4.12",
    "@types/redis": "^2.8.31",
    "nodemon": "^2.0.12",
    "ts-node-dev": "^1.1.8",
    "typescript": "^4.3.5"
  }
}

tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "lib",
    "declaration": true,
    "noImplicitAny": true,
    "declarationMap": true,
    "allowJs": true
  },
  "lib": ["es2015"]
}

JavaScript (Node.js, where I want to consume this library)
Simplified code...
const MyModule = require("my-module-name");
const myModule = new MyModule(); <--- this line is where the error happens

So the error that I'm getting is:
const myModule = new MyModule();
          ^
TypeError: MyModule is not a constructor

Which would indicate that MyModule is not even a class, but it is. I DO get intellisense for the types in my TS library, but I cannot use the class.
Here is the transpiled TS to JS code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const declarations_1 = require("./declarations");
class Communicator {
    constructor() {
         // constructor logic
        };

        // more methods...

}
exports.default = MyModule;

I've tried following multiple articles and guides, changed tsconfig.json, and added "type":"module" to package.json but for some reason, I simply cannot get this to work.
Any pointer would be very appreciated.
Comment: you are missing an `"` in the import statement
Comment: @flx updated question, forgot `"` when copying my code over
Answer: Try this
const MyModule = require("my-module-name").default;

const myModule = new MyModule();

Comment: thank you, this fixed it..... why is this notation needed? do you know if there is a way of packaging my TS library so that I can import it with `import` ?
Comment: I prefer do not use 'export default' in typescript, just 'export class MyClass'. In this case in javascript will be like 'const {MyClass}=require('mylibrary');'


Comparing two variance matrices

Question: I am looking for bibliographical reference for comparing two variance matrices with he following criterion:
$\text{Var}[X] \geq \text{Var}[Y] \quad \text{if} \quad \text{Var}[X]-\text{Var}[Y] \succeq 0$
This means that $X$ has greater variance than $Y$ if the difference of their variance matrices is positive semi-definite.
Any references to books or articles with citations that explain why this is a valid and common criterion to compare variability of random vectors is appreciated. If that is not possible any help on how to search for it would be ok.
Comment: Where did you encounter such a criterion?
Comment: @kjetil, I first saw of it in Wikipedia when studing the Gauss Markov theorem which asses that least squares is BLUE. I have used on my thesis and nobody complained. It makes sense because for any fixed $\alpha$, Var[$\alpha^t X$]$\geq$Var[$\alpha^t Y$].
Comment: Curious if you found such citations?
Answer: This order is the standard order on positive-definite matrices.  It is sometimes called the "Loewner order", or the cone ordering in the cone of positive-definite matrices.  Googling those terms will give many hits.  A book dedicated to inequalities and orders is Marshall, Olkin, Arnold:  "Inequalities: Theory
of Majorization and Its Applications",  chapter 14 D (second edition).
Comment: Go to google scholar and search flor "mathematical statistics loewner order"

Comparing two variance matrices


NSURLConnection crashes after all the data is uploaded and before connectionDidFinishLoading

Question: I have an uploader class (mediaUploader) which gets a NSData and uploads it to a particular server. This class is not singleton and can be instantiated (Although a singleton QueueManager class is implemented to dispatch each upload request to an object of mediaUploader ).
The problem is this implementation has been working for over a month now, but suddenly when I upload 2 files in a row the first one is uploaded with no problems and the connectionDidFinishLoading delegate method of NSURLConnection is called for it. But the second one is uploaded to 100% (I know because I'm tracing the progress of uploading in the connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:) but does not go to connectionDidFinish method nor the connectionDidFail.
After that connection:didReceiveResponse: and connection:didReceiveData: are also called (Normal transition for a normal upload also does this) but after these two usually the didFinishLoading method should be called which is not and my app crashes.
My stack trace is as follows:
#0  0x00000000 in 0x00000000 ()
#1  0x3186ffc2 in __65-[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]_block_invoke ()
#2  0x3186ff06 in -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:] ()
#3  0x3186fe20 in -[NSURLConnectionInternal _withActiveConnectionAndDelegate:] ()
#4  0x30b97106 in ___ZN27URLConnectionClient_Classic26_delegate_didFinishLoadingEU13block_pointerFvvE_block_invoke ()
#5  0x30b95d16 in ___ZN27URLConnectionClient_Classic18_withDelegateAsyncEPKcU13block_pointerFvP16_CFURLConnectionPK33CFURLConnectionClientCurrent_VMaxE_block_invoke_2 ()
#6  0x30e64980 in CFArrayApplyFunction ()
#7  0x30b2d7fa in RunloopBlockContext::perform() ()
#8  0x30b2d6b8 in MultiplexerSource::perform() ()
#9  0x30b2d54c in MultiplexerSource::_perform(void*) ()
#10 0x30efc25a in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ ()
#11 0x30efb72a in __CFRunLoopDoSources0 ()
#12 0x30ef9f1e in __CFRunLoopRun ()
#13 0x30e64f4e in CFRunLoopRunSpecific ()
#14 0x30e64d32 in CFRunLoopRunInMode ()
#15 0x35d69662 in GSEventRunModal ()
#16 0x337b016c in UIApplicationMain ()
#17 0x00263fc8 in main at /Users/mepla/Projects/BApp-ios/BApp/main.m:15

I also add the initialization of my connection in case there is a problem there:
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
    request.URL = requestURL;

    request.HTTPMethod = @"POST";

    NSUInteger timeinterval = [[NSDate date] timeIntervalSince1970];
    NSString *boundary = [NSString stringWithFormat:@"--%d", timeinterval];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uuid\"\r\n\r\n%@", uuid] dataUsingEncoding:NSUTF8StringEncoding]];

    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\"\r\n\r\n%@", username] dataUsingEncoding:NSUTF8StringEncoding]];

    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"host\"\r\n\r\n%@", XMPPDomain] dataUsingEncoding:NSUTF8StringEncoding]];

    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"filename\"; filename=\"%@\"\r\n", _mediaIdentifier] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[content dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:_uploadData]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:postbody];
    [request setTimeoutInterval:NSURLConnectionTimeout];

    _rawResponseData = [NSMutableData data];
    _connection = [[NSURLConnection alloc]
                   initWithRequest:request
                   delegate:self startImmediately:NO];

    [_connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                           forMode:NSDefaultRunLoopMode];

    [_connection start];

So, any help regarding this problem is much appreciated. Please keep in mind that this code was working fine for a long time and out of nowhere I'm getting this today. :(
Thank you in advance.
Comment: In addition, I also have a `mediaDownloader` class which works in exactly the same way and there is no problems with that. It works with as many download request as I pass to it.
Comment: try this: the Microsoft method: Product -> Clean. Quit XCode. Quit iOS Simulator. Detach all connected iOS-devices. Open XCode again, etc.
Comment: this has worked more than once for me! XCode is still a rather buggy dev-environment!
Comment: @Michael But the crash hasn't anything to do with Xcode!
Comment: so... you obviously haven't had this problem before, right?
Comment: @Melpa I would explicitly set a Content-Type header for the file. For multipart form data parts, the default content type (if not specified) equals `text/plain`. For a file with unknown content type you should specify `application/octet-stream`, otherwise the well known MIME type.
Comment: 1. You've shared the stack trace, but what is the exception code/address? What precisely was the crash? 2. The only thing that leaps to mind is if the delegate object is getting deallocated prematurely. I'd suggest implementing `dealloc` method in your delegate object, so you can see if this is the case.
Comment: @Rob I thought about a prematurely deallocated delegate as well, however, `NSURLConnection` _retains_ the delegate for the duration of the connection. :/  However, another cause of the issue would be if the delegate has been explicitly set to nil (accidentally of course).
Comment: did you do any upgrade between the working code and the non-working code? e.g. a upgrade from iOS 6 to iOS 7 or a upgrade from XCode 5.0 to XCode 5.1, or a upgrade from OSX 10.8 to OSX 10.9?
Comment: the real question is: why does an anonymous block inside `-_withConnectionAndDelegate:onlyActive:` call the NULL-function?
Comment: @Michael: Yes i have actually upgraded Xcode to 5.1 in this period. Actually i tried your first method: I closed everything up and removed all devices and my problem was solved. But before that I changed something in my UploadQueueHandler, so I dont really know which one actually solved the problem, but make your suggestion an answer and I'll try to reproduce the situation if it really works I'd mark that as correct answer. Anyways thank you and everybody who took the time to help ;)
Comment: @Rob: Thank you man but I checked and the delegate doesn't seem to be deallocated prematurely.
Answer: After a very close look at these lines:
[postbody appendData:[[NSString stringWithFormat:
    @"Content-Disposition: form-data; name=\"filename\"; filename=\"%@\"\r\n",
    _mediaIdentifier] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[content dataUsingEncoding:NSUTF8StringEncoding]];

shouldn't it be
[postbody appendData:[[NSString stringWithFormat:
    @"Content-Disposition: form-data; name=\"filename\"; filename=\"%@\"\r\n\r\n",
    _mediaIdentifier] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[content dataUsingEncoding:NSUTF8StringEncoding]];

?
Note: you may use a diff tool to make it obvious ;)
However, as already suggested in my comment, I would add a Content-Type header:
[postbody appendData:[[NSString stringWithFormat:
    @"Content-Disposition: form-data; name=\"filename\"; filename=\"%@\"\r\n",
    _mediaIdentifier] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[@"Content-Type: XXX/xxx\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[content dataUsingEncoding:NSUTF8StringEncoding]];

Comment: this doesn't explain the crash, though
Comment: It *may* be related to the crash IFF `NSURLConnection` will parse a multipart form-data message. However, I doubt it actually will. So, there's little chance the crash will disappear. Nonetheless, it's a bug - and will confuse the server and corrupt the received content.
Comment: Well because this exact code has been working smoothly for a period of time and I didnt change it I doubt that the Content-Disposition string would be the problem. On the other hand my server responds to unknown MIME_types it receives, so if the I'm sending unknown data I'd get back the server response immediately. Thank you very much for taking the time to comment here, Im gonna try some of the things you said but the problems appears to be solved. Ty ;)


Why is $\frac{a+1}{p^{\epsilon a}}$ bounded by a constant C that only depends on $\epsilon$?

Question: Why is $\frac{a+1}{p^{\epsilon a}}$ bounded by a constant C that only depends on $\epsilon$ ?
Here $a \geq 1$ is an integer ,$p$ is any prime and $\epsilon > 0$.
I tried considering the logarithm $\log\frac{a+1}{p^{\epsilon a}} = \log(a+1) - \epsilon a \log(p)$ but I would need to show this quantity is bounded above by a constant that depends only on $\epsilon$. Intuitively speaking with $p$ and $\epsilon$ fixed I think this quantity is bounded above for all $a$ since I think its negative for sufficiently large $a$, but I'm not sure how to argue this rigorously.
Comment: What have you tried?
Comment: $\epsilon$ had better be positive...
Comment: Hint: if you keep $a$ and $\epsilon$ fixed, the largest outcome is always for $p=2$.
Comment: Edited to include what I tried.
Comment: Thanks, now its clear why the constant wouldn't need to depend on $p$.
Answer: As mentioned in the comments,
$$\frac{a+1}{p^{\epsilon a}}\leq \frac{a+1}{2^{\epsilon a}},$$
since replacing $p$ with $2$ only decreases the denominator. We claim that $(a+1)/2^{\epsilon a}$ is eventually decreasing in $a$, which will show that it is bounded above. To do this, it suffices to show that, for large enough $a$,
$$\frac{a+1}{2^{\epsilon a}}\geq \frac{a+2}{2^{\epsilon(a+1)}}.$$
This is equivalent to
$$2^\epsilon\geq \frac{a+2}{a+1}=1+\frac1{a+1}.$$
Since the left side is some constant greater than $1$ (assuming $\epsilon>0$) and the right side goes to $1$ as $a\to\infty$, this is true for large enough $a$.
In fact, the maximum is reached near $a=\frac{1}{2^\epsilon-1}$, and you can use this to figure out how the constant $C$ varies in $\epsilon$.


Cannot connect S3 with Pyspark. Error Message: Bad Request, S3 Extended Request ID: my_extend_request_id

Question: I'm trying to connect s3 with spark, which it is installed on a ec2 cluster. The latter it is composed of a master and two slaves machines, all of them with 6GB of RAM and located in the Central europe (Fankfourt) AWS area.
I have installed AWSCLI and configured with my key and exported them into env.
I am using pyspark.
I start it using:
pyspark --master spark://my_ip:7077 --executor-memory 1G --packages org.apache.hadoop:hadoop-aws:2.7.3,com.amazonaws:aws-java-sdk-pom:1.11.274,com.databricks:spark-csv_2.10:1.1.0
The packge hadoop-aws: 2.7.3 is the same as the hadoop-common-2.7.3.jar version that is present onto Spark.
Once into pyspark I write the following to set up the s3 configuration:
sc._jsc.hadoopConfiguration (). set ("com.amazonaws.services.s3.enableV4", "true")
sc._jsc.hadoopConfiguration (). set ("fs.s3.awsAccessKeyId", "my_key")
sc._jsc.hadoopConfiguration (). set ("fs.s3.awsSecretAccessKey", "my_secret_key")
sc._jsc.hadoopConfiguration (). set ("fs.s3a.endpoint", "s3.eu-central-1.amazonaws.com")

I then go to write the following:
bucket = "my_bucket"
textFile = sc.textFile ("s3a: //" + bucket + "/tmp/small_file.csv")
textFile.take(5)

and Python throws me the following error:
Py4JJavaError: An error occurred while calling o36.partitions.
: com.amazonaws.services.s3.model.AmazonS3Exception: Status Code: 400, AWS Service: Amazon S3, AWS Request ID: my_request_id, AWS Error Code: null, AWS Error Message: Bad Request, S3 Extended Request ID: my_extend_request_id
    at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:798)
    at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:421)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:232)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3528)
    at com.amazonaws.services.s3.AmazonS3Client.headBucket(AmazonS3Client.java:1031)
    at com.amazonaws.services.s3.AmazonS3Client.doesBucketExist(AmazonS3Client.java:994)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:297)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94)
    at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
    at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:258)
    at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:229)
    at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:315)
    at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:199)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
    at scala.Option.getOrElse(Option.scala:121)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
    at org.apache.spark.api.java.JavaRDDLike$class.partitions(JavaRDDLike.scala:61)
    at org.apache.spark.api.java.AbstractJavaRDDLike.partitions(JavaRDDLike.scala:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)

Did I miss something?
Answer: You may change the config from
sc._jsc.hadoopConfiguration().set("com.amazonaws.services.s3.enableV4", "true")

to
sc.setSystemProperty("com.amazonaws.services.s3.enableV4", "true")

Comment: Even setting `sc.setSystemProperty("com.amazonaws.services.s3.enableV4", "true")` doesnt help. Any alternative?


Why does the positive root of a complex number output two solutions?

Question: I've pretty much just started the topic and didn't understand this point.
For $z=a+bi$
The root of $z$ is a complex number and can be expressed as $x+yi$
$ie. \sqrt{z}= x+yi$
$z=(x^{2}-y^{2})+(2xy)i$
Equating coefficients:
$a=x^{2}-y^{2}$ and $(2xy)i$
Solving simultaneously giving $x$ and $y$:
$x=\pm\sqrt{a+\sqrt{a^{2}+b^{2}}}, y=\frac{b}{2(\pm\sqrt{a+\sqrt{a^{2}+b^{2}}})}$
Essentially if $x_{+ve}=\sqrt{a+\sqrt{a^{2}+b^{2}}}$
Then $\sqrt{z} = \pm(x_{+ve}+iy_{+ve})$
This just seems wrong.
My understanding of the definition of a root was that the positive root of a number should only yield a positive answer.
$e.g. \sqrt{4} = 2$
I get behind the idea that $(\pm2)^{2}=4$ and I also get behind the idea that $(\pm(x_{+ve}+iy_{+ve}))^{2}=z$
Method two:
$z=|z|e^{i(\theta +2k\pi)}$ for $k\in\Bbb{Z}$
$\sqrt{z}=\sqrt{|z|}e^{\frac{i(\theta +2k\pi)}{2}}$
$\sqrt{z}=\sqrt{|z|}e^{i(\frac{\theta}{2}+\pi)}$ for $k=2n+1$ or $\sqrt{|z|}e^{i(\frac{\theta}{2})}$ for $k=2n, n\in\Bbb{Z}$
i.e. Two solutions
This method (if what I've done is valid), makes more sense than stating the positive root of a number has both a positive and a negative solution.
Am I missing something or is that the end of the story?
Comment: For complex numbers there is no "positive" or "negative", although the two roots do differ by a factor of $-1$.
Comment: You may want to read about multi-valued complex functions
Answer: I strongly urge you not to use the notation $\sqrt z$, unless $z$ is a non-negative real number.
Concerning the definition: a square root of a complex number $z$ is any complex number $w$ such that $w^2=z$. It turns out that every complex number other than $0$ has two distinct square roots ($0$ only has one square root, which is $0$ itself), and if $w$ is one of these roots, then the other one is $-w$. That's because if $w$ and $s$ are square roots of $z$, then $w^2=s^2=z$, but\begin{align}w^2=s^2&\iff w^2-s^2=0\\&\iff(w-s)(w+s)=0\\&\iff s=\pm w.\end{align}
So, you have tried to find a square root of $z=a+bi$ (with $a,b\in\Bbb R$) in two different ways you, in each approach, you got two distinct symmetric answers, which is what you should have got anyway.
Answer: In $\Bbb R$ there is an interaction between $<$ and the arithmetic operations $+$, $\times$ : For $a,b,c\in\Bbb R$ we have $a<b\implies a+c<b+c$ and we have $(a<b\land 0<c)\implies ac<bc$. It is not possible for this to work in $\Bbb C$ so we usually do not define any $<$ on $\Bbb C$ because it wouldn't have much (if anything) to do with the arithmetic.
Writing $\sqrt z$ when $z\in \Bbb C$ but $z\not\in \Bbb R^+\cup\{0\}$ should be avoided. There are two solutions to $x^2=z$ and it is ambiguous as to which one of them should be called $\sqrt z$.


Please how do I set a String variable to null in firestore with flutter?

Question: //I am trying to do this
String? userAvaterUrl = null;
//so I can do this:
FutureBuilder(
                          future: getPicture(),
                          builder: (context, snapshot) {
                            if (snapshot.hasData || snapshot.data != null) {
                              return CircleAvatar(
                                radius: width * 0.18,
                                backgroundImage:
                                    NetworkImage(snapshot.data.toString()),
                              );
                            } else {
                              return CircleAvatar(
                                  radius: width * 0.18,
                                  backgroundImage: AssetImage(
                                      "assets/images/icons2.png"));
                            }
                          },
                        ),

Comment: do you mind fixing the code you posted above?
Answer: this line:
  if(snapshot.hasData || snapshot.data != null) {
    ...

would check if the document has data. if you need to get the userAvaterUrl from the doc, you will need to use:
  backgroundImage: NetworkImage(snapshot.data['userAvaterUrl'].toString()),

but remember that even if snapshot.hasData || snapshot.data != null, snapshot.data['userAvaterUrl'] can be null and you may want to make sure that your app can handle that. so, instead, you may want to do this:
  if(snapshot.hasData &&
      snapshot.data != null &&
      snapshot.data['userAvaterUrl'] != null &&
      snapshot.data['userAvaterUrl'] is String
  ) {
    ... // return avatar with the network image
  } else {
    ... // return avatar with the asset image
  }

by the way, if you are using flutter 2 with null-safety, this:
  String? userAvaterUrl = null;

would just be
  String? userAvaterUrl; // no need to set to null

Comment: I want to do the:  String? userAvaterUrl;  so I can send a null value to firestore but its rejecting it. and also the solution above didn't work


Determinar o campo no ORDER BY RAND() no mysql

Question: Determinar qual campo da tabela vai ter ORDER BY RAND()
Exemplo: mostrar os dados aleatório de acordo com o campo (id_categoria)
Como que eu coloco um: WHERE ORDER BY RAND() id_categoria ???
Comment: Seria legal explicar um pouco melhor o que você quer na pergunta. Talvez, explicar textualmente o que você quer que aconteça de fato nos resultados, em vez de explicar apenas a query que está tentando.
Comment: Qual é o resultado que você quer? Por que precisa randomizar o id de um campo? Usar qualquer número randômico para ordem não daria na mesma?
Comment: Não entendi. Não existe isso de rand de um campo, `RAND()` simplesmente vai gerar um número aleatório qualquer.
Comment: O problema é na sintaxe?
Comment: Sim! Tem como determinar um campo da tabela, quando for usar o ORDER BY RAND() ?
Comment: Para "mostrar os dados de forma aleatória", faça a consulta no banco sem `ORDER BY` e use a função [`shuffle()`](http://www.php.net/manual/en/function.shuffle.php) do PHP para randomizar o resultado. (Escrevo isso baseado na tag `php` da pergunta).
Answer: Segundo a documentação não é possível obter resultados aleatórios por uma determinada coluna.

You cannot use a column with RAND() values in an ORDER BY clause,
because ORDER BY would evaluate the column multiple times. However,
you can retrieve rows in random order like this:
mysql> SELECT * FROM tbl_name ORDER BY RAND()
Você não pode usar uma coluna com valores RAND () em uma cláusula ORDER BY, pois ORDER BY avaliaria a coluna múltiplas vezes. No entanto, você pode recuperar linhas em ordem aleatória como esta:
mysql> SELECT * FROM tbl_name ORDER BY RAND()
Comment: Só acrescentando: não só "não é possível", como diz a documentação, como não consigo ver por que seria *necessário* :)
Comment: Junto com um `limit` em uma `subquery` podemos extrair categorias aleatorias de uma outra tabela. Ex: `SELECT * FROM produtos WHERE categoria_id IN (SELECT categoria_id FROM categorias GROUP BY categoria_id ORDER BY rand() LIMIT 5)`. Único case de uso que consegui imaginar :)
Comment: Com certeza é válido, mas queria ver um caso real pra isso :p
Answer: Vamos dizer que sua tabela tenha essa estrutura:
CREATE TABLE `cliente` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(50) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=latin1$$

Ficaria a SQL assim, porque quero que ele só faça rand() na id
SELECT a.id, b.nome from (SELECT id FROM cliente ORDER BY rand()) a join cliente b on b.id = a.id

No seu caso (exemplo por desconhecer totalmente sua estrutura)
SELECT a.id_categoria, b.* FROM (SELECT id_categoria, a.id FROM tabela ORDER BY rand()) a join tabela b on b.id = a.id

Comment: Qual diferença? Se for na ordem, cada execução vai dar uma ordem diferente, porque é rand.
Comment: Mas faz diferença deixar de usar a subquery e simplesmente usar ORDER BY RAND() na query de fora? Eu acho que não faz.
Comment: faz diferença acabei de realizar teste @bfavaretto


mvc enum viewmodel binding

Question: I want to bind an enum from a model to viewmodel. I understand this can be done via a select list conversion approach but there is no user input for this input. Do I have to change it to select list to use it in viewmodel?
The Model:
<code> public enum JobStatus
{
    Uncomplete=1, Complete=2
}

public class Job
{
public JobStatus JobStatus { get; set; }
}
</code>
The view model:
<code> public class JobDetailsVM

{
  public JobStatus JobStatus { get; set; }
}
</code>
The controller:
<code> var job = db.Jobs.Find(id);

        var JobDetails = new JobDetailsVM
        {
            IncidentID = job.IncidentID,
            ActionID = job.ActionID,
            JobStatus = job.JobStatus,
            CheckDone = job.CheckDone,
</code>
On:
<code>  JobStatus = job.JobStatus,
</code>
I get the following error: Error Cannot implicitly convert type 'WomsUICF.Models.JobStatus' to 'WomsUICF.Models.ViewModels.JobStatus'. An explicit conversion exists (are you missing a cast?)
Answer: It sounds like you have defined the same enum in two places. Is it possible to eliminate one of them? If not, you should be able to do this assignment via a cast:
<code>JobStatus = (WomsUICF.Models.ViewModels.JobStatus)job.JobStatus
</code>
Comment: Yep there both required..Uh... I really hope the solution wasn't this simple! It seems like what I am looking for.Let me see how it builds...
Comment: Hi this works perfectly. Just wondering if there anything I should know. the cast refers to the view model not domain, is that ok?

mvc enum viewmodel binding


Packing two different circles in a rectangle

Question: Given the dimension of a rectangle and radii of two circles, how can I decide if these two circles can fit in the rectangle?
I don't know if there is a formula to compute such a thing!
thank you :)
Comment: Well, to pack one circle in its diameter must be equal or smaller to the smaller sides of the triangle.  so to pack two circles in they must each have diameters smaller than the smaller side and the sum of the diameters must be less than that larger side.  So if the rectangle is 8 by 13 the diameters must each be less than 8 and the sum of the diameters must be less than 13. If your circles are 5 diameter, and 6 diameter they'll fit into any rectangle larger than 11 by 6.
Answer: In the figure below, let circle $E$ have radius $r_1$, circle $G$ have radius $r_2$ and the rectangle be $H$ high and $W$ wide.  You get the best fit by putting the circles in opposite corners.  First you need $H,W \gt 2r_1, 2r_2$ or one of the circles won't fit all by itself.  Then the coordinates of $E$ are $(r_1,H-r_1)$ and the coordinates of $G$ are $(W-r_2,r_2)$.  You need them to be at least $r_1+r_2$ apart, so the requirement is $$\sqrt{(W-r_1-r_2)^2+(H-r_1-r_2)^2} \gt r_1+r_2$$
Comment: @fleablood:  No, you don't need the long side as long as the sum of the diameters.  As my figure suggests, the diameters can overlap.  For a simple example, put two equal circles in a square.  The diagonal has a diameter plus $\sqrt 2$ times a diameter, so is $(2+2\sqrt 2)r$, which allows a diameter of $2-\sqrt 2$ times the side, greater than half the side.  Taking your example of circles of diameter $5$ and $6$ in a rectangle of height $6$, you only need $\frac {11}2+\sqrt{30} \approx 10.977$ of length
Comment: Isn't that rather complicated?  If instead of measuring corners you measured tangents to sides you'd get the far simpler $2(r_1 + r_2) \le \max (W,H)$ and $2\max(r_1,r_2) < \min (W, H)$.
Comment: Oh, good point.
Answer: To pack two circles tightly together is to touch them tangently.  The rectangle must be as wide as the longer diameter and the longer side as long as the sum of the diameters.
So if circle one  has diameter = $d_1$ and circle two has diameter = $d_2$ and $d_1 \ge d_2$ and the rectangle has sides $l$ and $w$ and $l \ge w$, then the two circles will fit if $d_1 \le w$ and $d_1 + d_2 \le l$.


AsyncTask onPostExecute listener

Question: Activity.java
//Activity stuff
MyClass mc = new MyClass();
mc.getText();

public void dosomething() {
    textview.setText(mc.getText());
}

MyClass.java
class MyClass {
    String text;
    public void setText() {
        class GetTextFromWEB extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {
                String url = urls[0];
                String output;
                //Getting text from web
                return output;
            }
            @Override
            protected void onPostExecute(String _text) {
                text = _text;
            }
        }
        String url = "google.com";
        //Doing with url something
        new GetText().execute(url);
    }
    public String getText() {return text;}
}

Promblem is - in activity setText do faster, then AsyncTask do it's job.
So when setText run, it's run like setText(null)
I need to check in activity, is asynk ended, so i have my text to set.
I hope i explained it
And i don't even need exactly AsyncTask, i need jsoup working, so if there is solution with another thread-class, with which jsoup will work, i can use it
Edit
class GetLyrics extends AsyncTask<String, Void, String> { //Class for getting lyrics
    private Context con;

    public GetLyrics(Context con) {
        this.con = con;
    }

    @Override
    protected String doInBackground(String... urls) {
        //do something
    }
    @Override
    protected void onPostExecute(String _lyrics) {
        lyrics = _lyrics;
        con.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ((TextView) findViewById(R.id.lyricsOutput)).setText(lyrics);
            }
        });
    }
}

Comment: Refer this http://stackoverflow.com/a/33918300/5567009
Comment: @NigamPatro thanks, i'll try
Comment: @NigamPatro nope, this doen't work for me, because i can't setText neither in `onPostExecute` nor in `new Asynctaskclass().execute(url);`  I need to listen in anouther place...
Comment: Have you created listener class and called the method in the `onPostExecute()` as given?
Comment: That is what I given answer there, can you post what you tried so far. So that I can give proper explanation as per your code.
Comment: @NigamPatro i have given more code. I tried your answers. But I CANT `setText` in `setLyrics()` ,because i don't have any TextView in it. I must `setText` outside `setLyrics()` -> i can't setText neither in `onPostExecute` nor in `new Asynctaskclass().execute(url);`
Comment: @NigamPatro i edit my question, may be now you will understand my problem
Answer: 1: Make my first project from my previous post and add some new lines in it to get data from http: api's.
public class Example extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("parameter1", "xyz"));
        params.add(new BasicNameValuePair("parameter2", "abc"));
        params.add(new BasicNameValuePair("parameter3", "opqr"));
        ServerConnection task = new ServerConnection(this, new ResultListener() {
            @Override
            public void result(String response) {
                Toast.make(this, response, Toast.LENGTH_LONG).show();
            }

            @Override
            public void loader(boolean visble) {
            }

            @Override
            public void connectionLost(String error) {
                Toast.make(this, error, Toast.LENGTH_LONG).show();
            }
        });
    }

    public class ServerConnection extends AsyncTask<String, String, String> implements Constant {
        ResultListener listener;
        private String Method = "GET";
        private List<NameValuePair> params = new ArrayList<NameValuePair>();

        private Context context;
        private ConnectionDetector cd;

        // public static Drawable drawable;
        public ServerConnection(Context context, ResultListener r) {
            this.context = context;
            this.listener = r;
            cd = new ConnectionDetector(context);
            this.execute();
        }

        public boolean isConnection() {
            return cd.isConnectingToInternet();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... arg0) {
            if (!isConnection()) {
                cancel(true);
                return "Sorry!connection lost,try again or later";
            }
            ApiResponse air = new ApiResponse();
            System.out.println("working hre" + "hi");
            String json;

            try {
                json = air.makeHttpRequest(URL, getMethod(), getParams());
            } catch (Exception e) {
                json = e.getMessage();
                cancel(true);
                return json;
            }

            return json;
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(String result) {
            listener.connectionLost(result);
            rl.connectionLost("Sorry!connection lost,try again or later");
            super.onCancelled(result);
        }

        @Override
        protected void onPostExecute(String result) {
            System.out.println("onpost" + result);
            listener.result(result);
            listener.loader(true);
            super.onPostExecute(result);
        }

        public String getMethod() {
            return Method;
        }

        public void setMethod(String method) {
            Method = method;
        }

        public List<NameValuePair> getParams() {
            return params;
        }

        public void setParams(List<NameValuePair> params) {
            this.params = params;
        }
    }

Example
Comment: Like i said, i have asynctask and it's execution in function, where is no textview. So i need check, is onPostExecute did run, or not
Comment: public void result(String response) {
   textView.setText(response);
      Toast.make(this,response,Toast.LENGTH_LONG).show();

    }
Comment: i have it in different classes.
Comment: May I know the full condition, where you need different approach. i can surely help you on this.
Answer: Call the method setting your text in the postExecute inside your AsyncTask or set the text directly on your postExecute method.
And wrap the line with setText() inside runOnUIThread (otherwise you will get an exception saying that the view can be accessed only by the thread that created it, since you are setting the text from async task).
Setting the text would be something like this
    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            ((TextView) findViewById(R.id.txtFieldName)).setText("your text");
        }
    });

That way you can quit worrying about checking if the async task is finished. But avoid doing complex ui operations like this. Since this is just setting the text on TextView, it should be allright.
Comment: I'm sorry, it sounds like what i need, but where i must paste it? In activity/settext/asynctask?
Comment: the line where you are setting the text should be replaced by the given snippet. Just remove the line inside the run block and paste your set text line of code.
Comment: also, like i said, set the text directly as above in postExecute.
Comment: I have an error `Cannot resolve getActivity()` in activity and in postExecute
Comment: you can pass the activity context as a parameter to the AsyncTask class constructor and use the context instead of getActivity()
Comment: How to right write it? `context.getActivity()...` and `context.runOnUiThread...` not seems to be working
Comment: where did you put it? can you share the code here? inside the postExecute in your AsyncTask or somewhere in the main activity as a method? Also try getApplicationContext()
Comment: that's correct. is this class for AsyncTask inside your activity class? if not, take this class inside the activity class and getActivity() will work just fine.
Comment: That's the problem. AsyncTask is inside anouther class. But i think i can replace it to activity, thanks

AsyncTask onPostExecute listener


Quarter note with dot

Question: How can I count the quarter note and dot in this example?
Answer: Whenever approaching difficult rhythms, I always recommend subdividing into smaller values. For this example, we can subdivide this into eighth notes.
Assuming this is in 4/4 time, we have eight eighth notes in the measure, often counted "1 & 2 & 3 & 4 &."
The first eighth note only takes up one of these eighth notes, the "1."
The next note, a dotted quarter, takes up three eighth notes. This is because the dot adds half the value of what precedes it. Since a quarter takes up two eighth notes, this dot add half of that two. Two and one make three, so this note is worth three eighth notes.
But it's also tied to another dotted quarter, so we have a value of three eighth notes tied to another three, so these two notes take up sixth eighth notes altogether.
Since the first note only took up the first "1," this next articulation begins on the "&" immediately after and takes us through '2 & 3 & 4.'
The final note is of course just a single eighth note, so it takes the final "&" of the measure.
So to count this, I recommend starting by saying, out loud, "1 & 2 & 3 & 4 &."
Then, remove the non-articulated eighth notes: 1 & (2 & 3 & 4) &.
Comment: Good to see there wasn't a dotted minim! More and more I see no division into two equal halves in 4/4 time, making it harder to read, for me at least. It may of course be the program used to print out. +1. I often simply count 1 to 8 eschewing the &.
Comment: @Tim I hadn't even imagined a dotted half there. Thanks for making my day worse! :-)

Quarter note with dot


Prove group and opposite group are isomorphic.

Question: Let $\langle G, ∗\rangle$ be a group, and suppose $∗'$ is a binary operation on $G$ defined by $a∗'b=b∗a$ for all $a,b \in G$. I also proved in the previous problem that $\langle G, ∗'\rangle$ was a group. What I'm thinking is:
Proof: Let $\langle G, ∗\rangle$ be a group, and suppose $∗'$ is a binary operation on $G$ defined by $a∗'b=b∗a$ for all $a,b \in G$. From the previous example we know that $\langle G, ∗'\rangle$ was a group. We know that $\langle G, ∗'\rangle$ contains all elements of that $\langle G, ∗\rangle$ since the only difference is the operation. Therefore, the groups have the same order, and thus are 1-to-1. Given that $*'$ is defined as $a∗'b=b∗a$ for all $a,b \in G$, this is essentially the commutative property to $*$. So, $a∗'b=b∗a$ and $b∗'a=a∗b$ thus making it an onto mapping. Therefore, they are bijective. Hence, $\langle G, ∗\rangle$ and $\langle G, ∗'\rangle$ are isomorphic as groups.
Is my reasoning sound?
Comment: One thing with [tag:solution-verification] questions is that users need to specify what it is about their proof/solution they're unsure of. Asking us to assess an entire proof is too broad.
Comment: Just for reference, such a structure is known as the [Opposite Group](https://en.wikipedia.org/wiki/Opposite_group)
Comment: There's only so much one can convey in 600 characters. Long, informal conversations are discouraged. People might seem terse, dismissive, impatient, *etc.*, but it's really a product of the forum style. We're friendly once you get to interact with us enough! $$\ddot\smile$$
Comment: From the tag wiki: "A question with this tag should include an explanation for why the argument presented is not convincing enough"
Comment: @Shaun, I'm sorry, but sometimes it seems like you do.
Comment: Your argument isn't enough.  You need to show that the natural map is in fact a group homomorphism.  (this is largely just a matter of writing down what that would mean).
Comment: @lulu the previous example was to show that the new binary operation created a group with $G$. So I showed associativity, that there was an identity, and inverses in the previous example. Do I need to do it again instead of just citing that we know from the previous example that it is a group?
Comment: Yes, I misread what you wrote and thought you still need to show it was a group.  So, given that that part is done, you still need to prove that the natural map is a group homomorphism.  It is obviously a set theoretic bijection but you need to prove that it respects the group law.
Comment: Correction:  the identity map does not work unless the group is abelian, so you need to find one that does.  The link I sent initially provides an example, but you might want to try to come up with one on your own.
Comment: This question has also been [asked before](https://math.stackexchange.com/q/1448683/104041).
Comment: See [this meta post](https://math.meta.stackexchange.com/a/20583/104041) about solution verification posts that are *sans* context.
Comment: @Shaun ok, I won't ask any more questions.
Comment: Please do ask more questions, @Tacosi! Don't be discouraged; you're new. We don't bite.
Answer:
Proof: Let $\langle G, ∗\rangle$ be a group, and suppose $∗'$ is a binary operation on $G$ defined by $a∗'b=b∗a$ for all $a,b \in G$. From the previous example we know that $\langle G, ∗'\rangle$ was a group. We know that $\langle G, ∗'\rangle$ contains all elements of that $\langle G, ∗\rangle$ since the only difference is the operation. Therefore, the groups have the same order, and thus are 1-to-1.

When you say 1-to-1, you need first give a map, $\phi:G\to G'$, and show $\phi$ is 1-to-1. How is your $\phi$ defined here?

Given that $*'$ is defined as $a∗'b=b∗a$ for all $a,b \in G$, this is essentially the commutative property to $*$. So, $a∗'b=b∗a$ and $b∗'a=a∗b$ thus making it an onto mapping. Therefore, they are bijective. Hence, $\langle G, ∗\rangle$ and $\langle G, ∗'\rangle$ are isomorphic as groups.

The general step to prove $G$ and $G'$ are isomorphic is:

give a map $\phi: G\to G'$
show $\phi$ is one to one
show $\phi$ is onto
show $\phi$ is a homomorphism, namely, $\phi(a*b)=\phi(a)*'\phi(b), ~~\forall a,b\in G$
Answer: The map $x \mapsto x^{-1}$ is an isomorphism from $(G,*)$ to $(G,*')$.
Answer: The identity mapping, although bijective, doesn't respect the group structure. So, you need to come up with a different bijection which is also a homomorphism of groups.
Hint : The new operation, although drastically different from the old one, does have the same identity element and the same inverse for each element.
How about the map $x \mapsto x^{-1}$ ?

As a side note, if you are aware of a bit of category theory (ignore, if not), then the new group is just the dual/opposite of $G$, considered as a single object groupoid. So what this says, is that a single object groupoid is isomorphic (as a category) to it's dual.
Comment: No, one-one doesn't follow from $G$ being in both groups. You can have mappings of a set into itself which are not one-one. In this case, the precise mapping $\phi : x \mapsto x^{-1}$ is one-one since as you said, each element has only one inverse. For ontoness of $\phi$, just observe that if $y \in G$, then $\phi(y^{-1}) = y$.
Comment: Do I express this as: let $\phi: \langle G,*\rangle \to \langle G,*'\rangle$ be defined as $\phi (x)=x^-1$? Then go through the $\phi (a*b)=\phi(a)*'\phi(b)$?
Comment: Yes. Precisely. You also need to check that $\phi$ is bijective.
Comment: doesn't 1-to-1 follow from G being in both groups? Or do I have to explicitly state that since $\phi(x)=x^-1$ and since each element has only one inverse that it is 1-to-1? For onto, I'm a little less clear what to do.


How do you RUN npm module node-inspector in OpenShift environment?

Question: I have made these failing attempts are on the OpenShift gear via SSH.
Attempt-1:
node-debug app.js
Node Inspector v0.12.7
Cannot start the server at 127.0.0.1:8080. Error: listen EACCES.

Attempt-2:
node-inspector
Node Inspector v0.12.7
Cannot start the server at 0.0.0.0:8080. Error: listen EACCES.

Attempt-3:
node --debug app.js
debugger listening on port 5858
Failed to open socket on port 5858, waiting 1000 ms before retrying

I don't know what the correct method is to get an installed node-inspector running in an OpenShift Node.JS Gear.
Comment: I was able to get it installed on the OpenShift environment but never able to get it running. I can not believe I am the only one in the OpenShift World wanting to do this.  Node-inspector is a great debugging tool. At some point you have to take your node app from your local network and put it in the cloud. Does that mean debugging is done? NO! So how can you continue to debug effectively? Node-Inspector is the obvious answer but no one has come back to me, not even Red Hat, with a solution. Do you have a cookbook recipe that works?
Comment: Did you find any more information on this problem?
Comment: Sorry I don't have a solution. I'm thinking maybe port forwarding may help to solve this.
Comment: Yes, I did too. It doesn't. Port forwarding is necessary but is not the missing part. :(  Thx. Wish I could afford to go to one of these Red Hat Conferences that cost $1400 to $2200, to push for an answer. But that is above the lone dev pay grade.
Answer: Not sure if this is way too late or if you have found a solution.
I've managed to get this working in OpenShift 'origin' on my local machine
I made use of the node4-rhel7 image so the following is specific (i.e entrypoint and adding to /usr/bin in the image), so change it accordingly
Here are the steps :-

create or update a Dockerfile that gave me the correct permissions (rw) for my node app
install node-inspector (npm install node-inspector --save)
add this script (call it start.sh - in a folder root/usr/bin) also remember to set execute permissions
if [ $# gt 0 ] && [ "$1" == "debug"]
then
  # assume default debug port of 5858
  node --debug name-of-startup.js
  node_modules/node-inspector/bin/inspector.js -p 9000 --save-live-edit=true
else
  node name-of-startup.js
fi
add a script called container-entrypoint also in a folder root/usr/bin
#!/bin/bash
exec "$@"
add this to your Dockerfile

ADD root /
ENTRYPOINT ["container-entrypoint"]
CMD ["start.sh"]

docker build -t name-of-your-image:version .
oc edit dc/name-of-your-node-pod
add port: 9000 and protocol: TCP in "spec.containers.ports"
add "command": [ "start.sh","debug"] in "spec.containers"
update the image to the newly built one on your local docker (name-of-your-image:version)
save (this will re-deploy your app) and execute 'oc get ep' (to get the endpoint of you app)
open chrome with with url http://your-app-endpoint:9000/?port=5858
you can now debug/set breakpoints etc and change code via the chrome interface - primitive but works like a charm :)


How to Deploye Nuxt.js app on google cloud run with intellij pluging

Question: I try to deploye Nuxt my app on google could run , with intellij pluging
Build [gcr.io/webapp-378307/differenceapp] succeeded

/home/ludow/.cache/google-cloud-tools-java/managed-cloud-sdk/LATEST/google-cloud-sdk/bin/gcloud run deploy differenceapp --quiet --image gcr.io/webapp-378307/differenceapp --platform managed --project webapp-378307 --memory 256Mi --timeout 300 --concurrency 80 --max-instances 1000 --cpu 1 --clear-env-vars --clear-cloudsql-instances --client-name "Cloud Code for IntelliJ" --client-version 23.1.1-222 --region europe-west1 --allow-unauthenticated --clear-vpc-connector
Deploying container to Cloud Run service [differenceapp] in project [webapp-378307] region [europe-west1]
Deploying...
Setting IAM Policy.............done
Creating Revision........................................................failed
Deployment failed
ERROR: (gcloud.run.deploy) The user-provided container failed to start and listen on the port defined provided by the PORT=3000 environment variable. Logs for this revision might contain more information.

Logs URL: https://console.cloud.google.com/logs/viewer?project=webapp-378307&resource=cloud_run_revision/service_name/differenceapp/revision_name/differenceapp-00007-joq&advancedFilter=resource.type%3D%22cloud_run_revision%22%0Aresource.labels.service_name%3D%22differenceapp%22%0Aresource.labels.revision_name%3D%22differenceapp-00007-joq%22
For more troubleshooting guidance, see https://cloud.google.com/run/docs/troubleshooting#container-failed-to-start

Failed to deploy to Cloud Run. Please ensure network is available, you are logged in to a valid GCP project, and try again.

i add this in my .env file
PORT=3000

Has anyone got a clue ?
Cordially
Answer: If you have error like :
ERROR: (gcloud.run.deploy) The user-provided container failed to start and listen on the port defined provided by the PORT=3000 environment variable. Logs for this revision might contain more information.

To make it work with Nuxt.js,
I add Dockerfile and install docker-buildx,
This my Dockerfile
# Use the official lightweight Node.js 18 image.
# https://hub.docker.com/_/node
FROM node:19-alpine

# Create and change to the app directory.
WORKDIR /usr/src/app

# Install app dependencies
COPY package*.json ./
RUN npm install

# Bundle app source
COPY . .

# Build the app
RUN npm run build

# Expose the port
EXPOSE 3000

# Start the app
CMD [ "yarn", "dev" ]


How to find a name containing "space" in a file?

Question: I have a BD.txt file with the following content:
Person1:Boston:20
Person2:New York:18
Person3:New York:25
Person4:New Orleans:30

I have to show how many people live in New York. I used:
cat BD.txt | grep New York | wc -l

The output was "3" instead of 2. "New York" has a space char on its name, and it finds only "new" (counting some results I don't want, like "New Orleans").
What should I use to find words containing sapce?
Answer: Use quotation marks around New York:
cat BD.txt | grep "New York" | wc -l

Answer: if I read the question correctly then it states to find the files having space in their name so below command will work
to find files in current directory only
find .  -maxdepth 1 -type f -name \*' '\* -prune

to find files in all subdirectories also
find . -type f -name \*' '\*


Tailwindcss Unable to remove gap in image please guide

Question: Screenshot https://i.stack.imgur.com/r3c94.jpg
Hello Developers please help me to remove that spaces in the right side image gap in the top
side of image how to reduce it, i searched alot and tested few method but not pass
please guide. I am new to this Tailwindcss. Thanks for the support.
See Image Screenshot
Please check screenshot
https://i.stack.imgur.com/r3c94.jpg

    Pricing
    Products
    About
    Careers
    Community

Get Started

        Bring Everyone Together To Build Better Products

        Manage makes it simple for software teams to plan day-to-day tasks while keeping the
        larger team goals in view.

        Get Started

```

  [1]: https://i.stack.imgur.com/OIgkL.png
  [2]: https://i.stack.imgur.com/sLYP2.png

Answer: Change items-center to items-start in Flex container div
Change this :

to


Cadastro de Usuario em Laravel

Question: Estou começando com laravel faz umas 2 semanas e automaticamente está chovendo de dúvidas.
Tenho um formulário de Cadastro com o seguinte botão abaixo:

<button type="button" class="btn btn-primary" id="cadastrar-usuario">
 Cadastrar Usuário
</button>

Tenho um UsuarioController.php que faz a listagem dos Usuários, lembrando que não estou usando a tabela users do laravel mesmo, irei usar posteriormente.
Gostaria de chamar uma function do meu controller.
Meu Controller está assim:
<?php namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;

class UsuarioController extends Controller {

    public function lista(){
        $usuarios = DB::select("select * from usuarios");

        return view('usuarios.listagem')->with('usuarios', $usuarios);
    }

}

?>

Como eu poderia chamar ele usando ajax?
Answer:  Primeiro você precisa criar uma rota no arquivo arquivo de rotas em app/Http/routes.php, acrescente:
Route::get('listausuarios', 'UsuarioController@lista');

No Javascript da sua View, considerando que você está usando JQuery, adicione o evento click ao botão:
jQuery(document).ready(function ($) {

    $("#cadastrar-usuario").on('click', function() {

        jQuery.get("listausuarios", function(data){
            //Tratamendo dos dados recebidos em formado json
        });
});

Vi que você retorna uma view, ao invés de um JSON no seu Controller. Teria que mudar isso também.
Mas caso você queira apenas pegar o click do botão e mudar de rota, você pode fazer da seguinte maneira no Javascript:
jQuery(document).ready(function ($) {

    $("#cadastrar-usuario").on('click', function() {
        window.location.href = 'listausuarios';
    });
});

Answer: Só para complementar a resposta anterior!
Você poderá utilizar a retorno do método da seguinte forma.
Criando um modelo da tabela dos usuários, usando o recurso do Eloquent e depois chamando o mesmo no seu Controlador:
return response()->json(Usuarios::all());

Ou retornando sua variável $usuarios dessa forma:
return response()->json(['usuarios' => $usuarios]);

Qualquer uma dessas formas lhe retornará um objeto JSON.
Comment: Não entende se é uma pergunta ou uma resposta?
Comment: Só para complementar a publicação da primeira resposta, de como ele pode efetuar o retorno em JSON
Comment: Quando for complementar você pode **Editar** sua resposta ou por os Complementos nos Comentários... Isso deixar sua pergunta/Resposta mais limpa e legível.

Cadastro de Usuario em Laravel


How to add a security group to a running EC2 Instance?

Question: I have an Amazon EC2 instance running and I will like to add another security group to that instance and then remove the current security group from that instance.  Is this possible?
Comment: Just to add a few more bits of information. We have two instances joint to two security groups.  We want to separate this and dedicate a security group per instance.
Answer: Update: As of January 2014, you can now change security groups for running AWS EC2 instances.
AWS Console
Simply right-click on an instance, and click on Change Security Group

Add/remove security groups as appropriate and click Assign Security Groups when done

EC2 Command Line
Use the following command:
ec2-modify-instance-attribute <instance-id> --group-id <group-id>

AWS Command Line
Use the following command:
aws ec2 modify-instance-attribute --instance-id i-12345 --groups sg-12345 sg-67890

Note, you must specify all security groups with which you'd like the instance associated.
Comment: The "Change Security Groups" option is present in the menu but disabled.  I'm using region ap-southeast-2.
Comment: this currently only applies to VPC instances. the security groups that a non-VPC instance belong to are fixed / immutable and are set when it's first launched. the only way to change them is to create a bundle from the existing instance and re-launch a new instance using the bundled ami.
Comment: What if my newly created security group isn't listed in the `Change Security Groups` modal?
Comment: This option may only be available inside of a VPC.  Older AWS accounts that were created pre-vpc and have instances running in EC2 classic mode will not be able to take advantage of this.
Comment: It is confusing that the CLI doesn't use comma-separated lists as in many other places.
Comment: Hey important note: the AWS CLI command listed will ***replace all groups*** with what is specified in the command. I basically just wiped out virtually all of the SGs across a vast swath of my infra.
Answer: Update 2015-02-27:
This is now possible, see the answer below.
Old reply:
Amazon's FAQ says it's not possible to define a security group anywhere but at launch time.
Comment: This answer is outdated. Now you can modify EC2 VPC Security Groups. See @hanxue answer below.
Comment: Thanks, I miss that question when I was browsing the FAQ. Thanks again.
Comment: Need to update!! See below answer
Answer: It is now possible to do this. Click on the actions menu and Change Security Groups - Select the Security Groups you would like to use.
Comment: Only in VPCs, I believe.
Comment: What if my newly created security group isn't listed in the Change Security Groups modal?
Comment: It appears so.  The "Change Security Groups" option is present in the menu but disabled for non-VPC instances.
Answer:
Create an AMI image from the instance you want to move to a different security group.
Launch a new instance using that image, now we can assign this new instance to a different security group.
Discard the previous instance.

This requires downtime on your instance. There may be some other options available using the API.
Answer: As towo said you can't change a security group of an instance anywhere but launch time.
Unless you are using a VPC where security groups differ from EC2 security groups.
This page outlines the differences between EC2 and VPC security groups.
http://docs.amazonwebservices.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html
So if you require the extra functionality of the VPC groups (Changing groups, control ingress/engress traffic, etc.), you may want to look at the additional functionality provided by VPCs.
Comment: Welcome to Server Fault! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Answer: If you are using boto3 you need to call modify_attribute and pass a list of group ids
http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Instance.modify_attribute
response = instance.modify_attribute(Groups=['string'])

Groups (list) --
  [EC2-VPC] Changes the security groups of the instance. You must
  specify at least one security group, even if it's just the default
  security group for the VPC. You must specify the security group ID,
  not the security group name.

Answer: As of 2016 Nov 24. above answer given by @hanxue is right but not complete. There are two types of instances in AWS: instances inside private cloud called vpc instances and  public instances called Ec2 Classic. You can only change security groups of VPC instances but not EC2-classic. Aws official documentation screenshot you would like to see.  docs you would like to see
Answer: In the new AWS GUI, just select the instance that you want to add a security group to, select actions on the top navigation area, then select on security. You are welcome
Answer: However according the this FAQ "modify the settings for the current security group - which will affect all instances running in the specific group" you can change gradually redefine the existing ones.
As I'm trying this now for my scenario through the EC2 console, my records where all erased!