问:
Rotating a 2d sub-array using numpy without aliasing effects
I would like to rotate only the positive value pixels in my 2d array some degree about the center point. The data represents aerosol concentrations from a plume dispersion model, and the chimney position is the origin of rotation.

I would like to rotate this dispersion pattern given the wind direction.

The concentrations are first calculated for a wind direction along the x-axis and then translated to their rotated position using a 2d linear rotation about the center point of my array (the chimney position) for all points whose concentration is > 0.
The input X,Y to the rotation formula are pixel indexes.

My problem is that the output is aliased since integers become floats. In order to obtain integers, I rounded up or down the output. However, this creates null cells which become increasingly numerous as the angle increases.

Can anyone help me find a solution to my problem? I would like to fix this problem if possible using numpy, or a minimum of packages...

The part of my script that deals with computing the concentrations and rotating the pixel by 50°N is the following. Thank you for your help.

```<code>def linear2D_rotation(xcoord,ycoord,azimuth_degrees):
    radians = (90 - azimuth_degrees) * (np.pi / 180) # in radians
    xcoord_rotated = (xcoord * np.cos(radians)) - (ycoord * np.sin(radians))
    ycoord_rotated = (xcoord * np.sin(radians)) + (ycoord * np.cos(radians))
    return xcoord_rotated,ycoord_rotated

u_orient = 50 # wind orientation in degres from North
kernel = np.zeros((NpixelY, NpixelX))  # initialize matrix
Yc = int((NpixelY - 1) / 2)  # position of central pixel
Xc = int((NpixelX - 1) / 2)  # position of central pixel

nk = 0
for Y in list(range(0,NpixelX)):
    for X in list(range(0,NpixelY)):
        # compute concentrations only in positive x-direction
        if (X-Xc)>0:
            # nnumber of pixels to origin point (chimney)
            dx = ((X-Xc)+1)
        dy = ((Y-Yc)+1)
        # distance of point to origin (chimney)
        DX = dx*pixel_size_X
        DY = dy*pixel_size_Y
        # compute diffusivity coefficients
        Sy, Sz = calcul_diffusivity_coeff(DX, stability_class)
        # concentration at ground level below the centerline of the plume
        C = (Q / (2 * np.pi * u * Sy * Sz)) * \
            np.exp(-(DY / (2 * Sy)) ** 2) * \
            (np.exp(-((Z - H) / (2 * Sz)) ** 2) + np.exp(-((Z + H) / (2 * Sz)) ** 2))  # at point away from center line
        C = C * 1e9  # convert MBq to Bq

        # rotate only if concentration value at pixel is positive
        if C > 1e-12:
            X_rot, Y_rot = linear2D_rotation(xcoord=dx, ycoord=dy,azimuth_degrees=u_orient)
            X2 = int(round(Xc+X_rot))
            Y2 = int(round(Yc-Y_rot)) # Y increases downwards
            # pixels that fall out of bounds -> ignore
            if (X2 > (NpixelX - 1)) or (X2 < 0) or (Y2 > (NpixelY - 1)):
                continue
            else:
                # replace new pixel position in kernel array
                kernel[Y2, X2] = C
</code>```

The original array to be rotated

The rotated array by 40°N showing the data loss

答:
Your problem description is not 100% clear, but here are a few recommendations:

1.) Don't reinvent the wheel. There are standard solutions for things like rotating pixels. Use them! In this case

scipy.ndimage.affine_transform for performing the rotation

a homogeneous coordinate matrix for specifying the rotation

nearest neighbor interpolation (parameter order=0 in code below).

2.) Don't loop where not necessary. The speed you gain by not processing non-positive pixels is nothing against the speed you lose by looping. Compiled functions can ferry around a lot of redundant zeros before hand-written python code catches up with them.

3.) Don't expect a solution that maps pixels one-to-one because it is a fact that there will be points that are no ones nearest neighbor and points that are nearest neighbor to multiple other points. With that in mind, you may want to consider a higher order, smoother interpolation.

Comparing your solution to the standard tools solution we find that the latter

gives a comparable result much faster and without those hole artifacts.

Code (without plotting). Please note that I had to transpose and flipud to align the results :

```<code>import numpy as np
from scipy import ndimage as sim
from scipy import stats

def mock_data(n, Theta=50, put_neg=True):
    y, x = np.ogrid[-20:20:1j*n, -9:3:1j*n, ]
    raster = stats.norm.pdf(y)*stats.norm.pdf(x)
    if put_neg:
        y, x = np.ogrid[-5:5:1j*n, -3:9:1j*n, ]
        raster -= stats.norm.pdf(y)*stats.norm.pdf(x)
        raster -= (stats.norm.pdf(y)*stats.norm.pdf(x)).T
    return {'C': raster * 1e-9, 'Theta': Theta}

def rotmat(Theta, offset=None):
    theta = np.radians(Theta)
    c, s = np.cos(theta), np.sin(theta)
    if offset is None:
        return np.array([[c, -s] [s, c]])
    R = np.array([[c, -s, 0], [s, c,0], [0,0,1]])
    to, fro = np.identity(3), np.identity(3)
    offset = np.asanyarray(offset)
    to[:2, 2] = offset
    fro[:2, 2] = -offset
    return to @ R @ fro

def f_pp(C, Theta):
    m, n = C.shape
    clipped = np.maximum(0, 1e9 * data['C'])
    clipped[:, :n//2] = 0
    M = rotmat(Theta, ((m-1)/2, (n-1)/2))
    return sim.affine_transform(clipped, M, order = 0)

def linear2D_rotation(xcoord,ycoord,azimuth_degrees):
    radians = (90 - azimuth_degrees) * (np.pi / 180) # in radians
    xcoord_rotated = (xcoord * np.cos(radians)) - (ycoord * np.sin(radians))
    ycoord_rotated = (xcoord * np.sin(radians)) + (ycoord * np.cos(radians))
    return xcoord_rotated,ycoord_rotated

def f_OP(C, Theta):
    kernel = np.zeros_like(C)
    m, n = C.shape
    for Y in range(m):
        for X in range(n):
            if X > n//2:
                c = C[Y, X] * 1e9
                if c > 1e-12:
                    dx = X - n//2 + 1
                    dy = Y - m//2 + 1
                    X_rot, Y_rot = linear2D_rotation(xcoord=dx, ycoord=dy,azimuth_degrees=Theta)
                    X2 = int(round(n//2+X_rot))
                    Y2 = int(round(m//2-Y_rot)) # Y increases downwards
                    # pixels that fall out of bounds -> ignore
                    if (X2 > (n - 1)) or (X2 < 0) or (Y2 > (m - 1)):
                        continue
                    else:
                        # replace new pixel position in kernel array
                        kernel[Y2, X2] = c
    return kernel

n = 100
data = mock_data(n, 70)
</code>```

Body:
I would like to rotate only the positive value pixels in my 2d array some degree about the center point. The data represents aerosol concentrations from a plume dispersion model, and the chimney position is the origin of rotation.

I would like to rotate this dispersion pattern given the wind direction.

The concentrations are first calculated for a wind direction along the x-axis and then translated to their rotated position using a 2d linear rotation about the center point of my array (the chimney position) for all points whose concentration is > 0.
The input X,Y to the rotation formula are pixel indexes.

My problem is that the output is aliased since integers become floats. In order to obtain integers, I rounded up or down the output. However, this creates null cells which become increasingly numerous as the angle increases.

Can anyone help me find a solution to my problem? I would like to fix this problem if possible using numpy, or a minimum of packages...

The part of my script that deals with computing the concentrations and rotating the pixel by 50°N is the following. Thank you for your help.

def linear2D_rotation(xcoord,ycoord,azimuth_degrees):
    radians = (90 - azimuth_degrees) * (np.pi / 180) # in radians
    xcoord_rotated = (xcoord * np.cos(radians)) - (ycoord * np.sin(radians))
    ycoord_rotated = (xcoord * np.sin(radians)) + (ycoord * np.cos(radians))
    return xcoord_rotated,ycoord_rotated

u_orient = 50 # wind orientation in degres from North
kernel = np.zeros((NpixelY, NpixelX))  # initialize matrix
Yc = int((NpixelY - 1) / 2)  # position of central pixel
Xc = int((NpixelX - 1) / 2)  # position of central pixel

nk = 0
for Y in list(range(0,NpixelX)):
    for X in list(range(0,NpixelY)):
        # compute concentrations only in positive x-direction
        if (X-Xc)>0:
            # nnumber of pixels to origin point (chimney)
            dx = ((X-Xc)+1)
        dy = ((Y-Yc)+1)
        # distance of point to origin (chimney)
        DX = dx*pixel_size_X
        DY = dy*pixel_size_Y
        # compute diffusivity coefficients
        Sy, Sz = calcul_diffusivity_coeff(DX, stability_class)
        # concentration at ground level below the centerline of the plume
        C = (Q / (2 * np.pi * u * Sy * Sz)) * \
            np.exp(-(DY / (2 * Sy)) ** 2) * \
            (np.exp(-((Z - H) / (2 * Sz)) ** 2) + np.exp(-((Z + H) / (2 * Sz)) ** 2))  # at point away from center line
        C = C * 1e9  # convert MBq to Bq

        # rotate only if concentration value at pixel is positive
        if C > 1e-12:
            X_rot, Y_rot = linear2D_rotation(xcoord=dx, ycoord=dy,azimuth_degrees=u_orient)
            X2 = int(round(Xc+X_rot))
            Y2 = int(round(Yc-Y_rot)) # Y increases downwards
            # pixels that fall out of bounds -> ignore
            if (X2 > (NpixelX - 1)) or (X2 < 0) or (Y2 > (NpixelY - 1)):
                continue
            else:
                # replace new pixel position in kernel array
                kernel[Y2, X2] = C

The original array to be rotated

The rotated array by 40°N showing the data loss

Body:
Your problem description is not 100% clear, but here are a few recommendations:

1.) Don't reinvent the wheel. There are standard solutions for things like rotating pixels. Use them! In this case

scipy.ndimage.affine_transform for performing the rotation

a homogeneous coordinate matrix for specifying the rotation

nearest neighbor interpolation (parameter order=0 in code below).

2.) Don't loop where not necessary. The speed you gain by not processing non-positive pixels is nothing against the speed you lose by looping. Compiled functions can ferry around a lot of redundant zeros before hand-written python code catches up with them.

3.) Don't expect a solution that maps pixels one-to-one because it is a fact that there will be points that are no ones nearest neighbor and points that are nearest neighbor to multiple other points. With that in mind, you may want to consider a higher order, smoother interpolation.

Comparing your solution to the standard tools solution we find that the latter

gives a comparable result much faster and without those hole artifacts.

Code (without plotting). Please note that I had to transpose and flipud to align the results :

import numpy as np
from scipy import ndimage as sim
from scipy import stats

def mock_data(n, Theta=50, put_neg=True):
    y, x = np.ogrid[-20:20:1j*n, -9:3:1j*n, ]
    raster = stats.norm.pdf(y)*stats.norm.pdf(x)
    if put_neg:
        y, x = np.ogrid[-5:5:1j*n, -3:9:1j*n, ]
        raster -= stats.norm.pdf(y)*stats.norm.pdf(x)
        raster -= (stats.norm.pdf(y)*stats.norm.pdf(x)).T
    return {'C': raster * 1e-9, 'Theta': Theta}

def rotmat(Theta, offset=None):
    theta = np.radians(Theta)
    c, s = np.cos(theta), np.sin(theta)
    if offset is None:
        return np.array([[c, -s] [s, c]])
    R = np.array([[c, -s, 0], [s, c,0], [0,0,1]])
    to, fro = np.identity(3), np.identity(3)
    offset = np.asanyarray(offset)
    to[:2, 2] = offset
    fro[:2, 2] = -offset
    return to @ R @ fro

def f_pp(C, Theta):
    m, n = C.shape
    clipped = np.maximum(0, 1e9 * data['C'])
    clipped[:, :n//2] = 0
    M = rotmat(Theta, ((m-1)/2, (n-1)/2))
    return sim.affine_transform(clipped, M, order = 0)

def linear2D_rotation(xcoord,ycoord,azimuth_degrees):
    radians = (90 - azimuth_degrees) * (np.pi / 180) # in radians
    xcoord_rotated = (xcoord * np.cos(radians)) - (ycoord * np.sin(radians))
    ycoord_rotated = (xcoord * np.sin(radians)) + (ycoord * np.cos(radians))
    return xcoord_rotated,ycoord_rotated

def f_OP(C, Theta):
    kernel = np.zeros_like(C)
    m, n = C.shape
    for Y in range(m):
        for X in range(n):
            if X > n//2:
                c = C[Y, X] * 1e9
                if c > 1e-12:
                    dx = X - n//2 + 1
                    dy = Y - m//2 + 1
                    X_rot, Y_rot = linear2D_rotation(xcoord=dx, ycoord=dy,azimuth_degrees=Theta)
                    X2 = int(round(n//2+X_rot))
                    Y2 = int(round(m//2-Y_rot)) # Y increases downwards
                    # pixels that fall out of bounds -> ignore
                    if (X2 > (n - 1)) or (X2 < 0) or (Y2 > (m - 1)):
                        continue
                    else:
                        # replace new pixel position in kernel array
                        kernel[Y2, X2] = c
    return kernel

n = 100
data = mock_data(n, 70)


来源: stackexchange

问:
Ionic 3+: how to navigate away from tabbed interface?
My Ionic application first loads LoginComponent and when user successfully logs in, loads the main TabsComponent view which allows to switch between corresponding child views.

I am trying to make it load standalone LoginComponent without tabbed interface, and that is not working (once switched to TabsComponent, I cannot navigate away from tabbed interface).

I've tried following commands from under one of TabsComponent child views:

```<code>this.navCtrl.push(LoginComponent);      // Loads as a child view
this.navCtrl.setRoot(LoginComponent);   // Loads as a child view
this.navCtrl.popAll();                  // Error: navigation stack needs at least one root page
this.navCtrl.popTo(LoginComponent);     // Error: navigation stack needs at least one root page
</code>```

I've went through Ionic documentation many times but I haven't found an answer to this question. What am I missing?

答:
I've solved this by injecting TabsComponent into it's child component, and then calling this.navCtrl.setRoot(LoginComponent); in a function inside TabsComponent:

```<code>// Child class of TabsComponent (loaded via tab click)
export class SettingsComponent {
    constructor(@Inject(forwardRef(() => TabsComponent)) private tabsComponent: TabsComponent) {
    }

    logOut(): void {
        this.tabsComponent.switchToLoginPage():
    }
}
</code>```

And switchToLoginPage on TabsComponent:

```<code>import {Component, forwardRef, Inject} from '@angular/core';
// ...
export class TabsComponent {
    constructor(private navCtrl: NavController) {
    }

    switchToLoginPage(): void {
        this.navCtrl.setRoot(LoginComponent);
    }
}
</code>```

Based on this example: How do I inject a parent component into a child component?

If there is a better way I'd love to know about, otherwise hope this solution would help anyone.

ContentLicense: CC BY-SA 3.0

Body:
My Ionic application first loads LoginComponent and when user successfully logs in, loads the main TabsComponent view which allows to switch between corresponding child views.

I am trying to make it load standalone LoginComponent without tabbed interface, and that is not working (once switched to TabsComponent, I cannot navigate away from tabbed interface).

I've tried following commands from under one of TabsComponent child views:

this.navCtrl.push(LoginComponent);      // Loads as a child view
this.navCtrl.setRoot(LoginComponent);   // Loads as a child view
this.navCtrl.popAll();                  // Error: navigation stack needs at least one root page
this.navCtrl.popTo(LoginComponent);     // Error: navigation stack needs at least one root page

I've went through Ionic documentation many times but I haven't found an answer to this question. What am I missing?

Body:
I've solved this by injecting TabsComponent into it's child component, and then calling this.navCtrl.setRoot(LoginComponent); in a function inside TabsComponent:

// Child class of TabsComponent (loaded via tab click)
export class SettingsComponent {
    constructor(@Inject(forwardRef(() => TabsComponent)) private tabsComponent: TabsComponent) {
    }

    logOut(): void {
        this.tabsComponent.switchToLoginPage():
    }
}

And switchToLoginPage on TabsComponent:

import {Component, forwardRef, Inject} from '@angular/core';
// ...
export class TabsComponent {
    constructor(private navCtrl: NavController) {
    }

    switchToLoginPage(): void {
        this.navCtrl.setRoot(LoginComponent);
    }
}

Based on this example: How do I inject a parent component into a child component?

If there is a better way I'd love to know about, otherwise hope this solution would help anyone.


问:
Does RSS push or pull updates?
Please note: Although I mention Java 8 I think the answer here is really language-agnostic.

I'm building a simple Java 8 web service that will aggregate RSS feeds across various topics and make their content available by request. I've never worked with RSS before and all the videos I have found are just about how to generate an RSS file for your lame blog, and all the articles I have found on "Java and RSS" are just examples of parsing XML.

I'm curious: does RSS work as push or pull?

By "push" I mean: say "RSS feed A" publishes an update to their RSS file on their service (say http://rss-a.example.com/rss/news.rss). Does their server somehow send a message to my backend, alerting my backed that an update is ready?; or

By "pull" I mean: is my backend just responsible for pinging all of the RSS feed URLs every n seconds and pulling in new content as its published?

Also, how do Java libraries like ROME snap into either push/pull architecture above?

答:
RSS is just a data format. Nothing more. It neither pushes nor pulls.

It is typically accessed by polling (and the format includes the ability to specify how often it should be polled as metadata).

This doesn't prevent you from creating a (or finding an existing) a service which you can send the data to a client instead of having them request it over HTTP. Nor one where you send a message informing them that the feed has updated and they should make a new HTTP request.

Title: Does RSS push or pull updates?


问:
Good uses for Apache CollectionUtils
I found the CollectionUtils class a year or so ago and a few of the methods like, collect, and transform seem really cool, however, I have yet to find a use where it would not by syntactically cleaner and\or easier to just write the logic with a simple loop.

Has any found a unique\useful use for these methods (transform, predicatedCollection, collect, etc) e.g. the methods that take a transformer or predicate as an argument?

答:
Although I agree with Uri in principle, without closures or function literals or whatever, Java imposes a pretty high syntactic cost to actually use methods like collect, transform, etc. In a lot of cases, the actual lines of code is the same or greater than if you had written the simple loop. addAll, removeAll, and all their friends that don't take function objects as arguments are indispensible though.

All of this also applies to the equally good Google Collections API.

It's sad that Sun has the power to fix these issues in Java 7, but it appears they won't. Cowards.

ContentLicense: CC BY-SA 2.5

Title: Good uses for Apache CollectionUtils

OwnerDisplayName: Dave Ray


问:
hide lines of text not fully visible with javascript & css
I think this might be impossible, but is there some way using JQuery to prevent lines of text not fully visible from showing up on the screen when a user scrolls until the entire line is visible? That is, we want to prevent something like this from showing up:

Thanks!

答:
I don't know if there is something out there to do that. But I think it will cause confusion more that it would make any visual enhancement ever. A user will not be happy when scrolling down and finds lines just "popup" suddenly, in opposite to normally easing out as a result of scrolling action.

After all, when we speak about a scrollable HTML element with scrollbars visible, a user is aware text might be partially shown and that is normal and needs to be scrolled down to read the remaining. I really would not recommend that.

But for a technical answer, I think you would need to fix the CSS line-height property of that scrolling element, say make it 8px or whatever fits your layout. Then, capture the scroll event and devide the jQuery scrollTop() by that CSS line-height, then check the results: if it have a fraction then that means there is a "partially visible" line. Don't forget aout margin and padding that can cause mistakes when calculating.


问:
ESXi remote access
i have a server with ESXi in my local network.
i can connect to it via vSphere from my local network
but can't connect from internet. Some people http://www.logicalsolutions.co.nz/connect-vsphere-client-externally/ achived by port forwarding so did i.

```<code>ESXi settings
ip 192.168.100.118
mask 255.255.255.0
gateway 192.168.100.1

Router settings
incoming port 443 forwarded to 443 of server 192.168.100.118 (my ESXi)
incoming port 902 forwarded to 902 of server 192.168.100.118 (my ESXi)
</code>```

vSphere "public ip":port

still no connection.

So i thought if the problem was with router and forwarded some port to my local sqlserver port. It works

Maybe there are some settings where can i enable public access to ESXi.

答:
better solution is to use  using the vSphere Update Manager to upgrade Esxi hosts.

that need to exist an VCenter server.

or on the console bash (with esx cli) use update command:

```<code>esxcli software profile update -d https://hostupdate.vmware.com/software/VUM/PRODUCTION/main/vmw-depot-index.xml -p ESXi-6.5.0-20170702001-standard
</code>```

Title: ESXi remote access

Body:
i have a server with ESXi in my local network.
i can connect to it via vSphere from my local network
but can't connect from internet. Some people http://www.logicalsolutions.co.nz/connect-vsphere-client-externally/ achived by port forwarding so did i.

ESXi settings
ip 192.168.100.118
mask 255.255.255.0
gateway 192.168.100.1

Router settings
incoming port 443 forwarded to 443 of server 192.168.100.118 (my ESXi)
incoming port 902 forwarded to 902 of server 192.168.100.118 (my ESXi)

vSphere "public ip":port

still no connection.

So i thought if the problem was with router and forwarded some port to my local sqlserver port. It works

Maybe there are some settings where can i enable public access to ESXi.

Body:
better solution is to use  using the vSphere Update Manager to upgrade Esxi hosts.

that need to exist an VCenter server.

or on the console bash (with esx cli) use update command:

esxcli software profile update -d https://hostupdate.vmware.com/software/VUM/PRODUCTION/main/vmw-depot-index.xml -p ESXi-6.5.0-20170702001-standard


问:
Strange behavior with flashdata in codeigniter
I have found very strange behavior of "if" condition and session flashdata in codeigniter,

```<code>public function edit_equip($equip_id, $company_id) {
        $this->data['section_title'] = 'Edit Equipment';
        $this->data['equip_detail'] = $equip_detail = $this->common->select_data_by_id('equipment', 'id', $equip_id, '*', array());
        if (empty($equip_detail)) {
            $this->session->set_flashdata('error', 'Error Ouccrred. Try Again!');
            redirect('Company/equipment/' . $company_id, 'refresh');
        }
       //some other code
        $this->load->view('company/edit_equip', $this->data);
    }
</code>```

this is a function of my Equipment class. Now when I call below url like,
http://localhost/scale/Equipment/edit_equip/1/2

then edit view will open correctly. but now when I press F5 button or browser refresh button then it is showing "Error Ouccrred. Try Again!" flash message which I have set in above if condition. I am not understand why this is happening, because $equip_detail contains data and I have also try to die in it but it is not going into if which is correct so why only $this->session->set_flashdata('error', 'Error Ouccrred. Try Again!');
is providing effect?

in conclusion my code is not running if block but if i press F5 or browser refresh button after first time my view is loaded it is showing me error message which is set in if condition, but my code is not going to it otherwise it has to redirect but it is loading view page with flash message.

I have only set this flash message at only one place as per above code. I am using codeigniter 3.1.6

Please can anyone explain me this?

答:
the CI manual says:

CodeIgniter supports “flashdata”, or session data that will only be
  available for the next request, and is then automatically cleared.

F5 is sending a new request, so flashdata is cleared

Body:
I have found very strange behavior of "if" condition and session flashdata in codeigniter,

public function edit_equip($equip_id, $company_id) {
        $this->data['section_title'] = 'Edit Equipment';
        $this->data['equip_detail'] = $equip_detail = $this->common->select_data_by_id('equipment', 'id', $equip_id, '*', array());
        if (empty($equip_detail)) {
            $this->session->set_flashdata('error', 'Error Ouccrred. Try Again!');
            redirect('Company/equipment/' . $company_id, 'refresh');
        }
       //some other code
        $this->load->view('company/edit_equip', $this->data);
    }

this is a function of my Equipment class. Now when I call below url like,
http://localhost/scale/Equipment/edit_equip/1/2

then edit view will open correctly. but now when I press F5 button or browser refresh button then it is showing "Error Ouccrred. Try Again!" flash message which I have set in above if condition. I am not understand why this is happening, because $equip_detail contains data and I have also try to die in it but it is not going into if which is correct so why only $this->session->set_flashdata('error', 'Error Ouccrred. Try Again!');
is providing effect?

in conclusion my code is not running if block but if i press F5 or browser refresh button after first time my view is loaded it is showing me error message which is set in if condition, but my code is not going to it otherwise it has to redirect but it is loading view page with flash message.

I have only set this flash message at only one place as per above code. I am using codeigniter 3.1.6

Please can anyone explain me this?


问:
Android Kotlin : TextView.text not working as expected
I have an app that makes user sign in with Firebase if they are not already signed in. If user signs in their user profile info shows properly. Upon closing the app and reopening the user name and email does not set and goes to my defaulted text. But if I sign out and back in it will show. I feel like it has something to do with updating ui but stuck.

I can post code after my lunch break is over if needed

update with code

This is the relevent code in MainActivity this is where I check if user is logged in if so allow them to go from there if not to start signin activity.

```<code>class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

val TAG = "MainActivity"

var mAuth: FirebaseAuth? = null
var mUser: FirebaseUser? = null
var userEmailTV: TextView? = null
var userDispNameTV: TextView? = null
val RC_SIGN_IN = 123

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    val toggle = ActionBarDrawerToggle(
            this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
    drawer_layout.addDrawerListener(toggle)
    toggle.syncState()
    nav_view.setNavigationItemSelectedListener(this)

}

 override fun onStart() {
    super.onStart()

    mAuth = FirebaseAuth.getInstance()
    mUser = mAuth?.currentUser

    if (mUser != null) {

        userEmailTV = findViewById<View>(R.id.userEmail) as TextView?
        userEmailTV?.text = mUser?.email
        userDispNameTV = findViewById<View>(R.id.userName) as TextView?
        userDispNameTV?.text = mUser?.displayName

        Log.i(TAG, "User Display Name : ${mUser?.displayName}")
        Log.i(TAG, "Users Email :  ${mUser?.email}")

    } else {
        startActivityForResult(
                // Get an instance of AuthUI based on the default app
                AuthUI.getInstance().createSignInIntentBuilder().build(),
                RC_SIGN_IN)
    }

}
</code>```

This is the layout info that holds the user profile info inside the navigation drawer

```<code> <TextView
    android:id="@+id/userName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"
    android:text="Username"/>

<TextView
    android:id="@+id/userEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="youremail@something.com"/>
</code>```

答:
My theory after much trial and error and research is..... that this problem is not due to the TextView being initialized in the wrong spot as others thought in the comments above but.  Due to the fact that the navigation header view has not had time to inflate. I will work on coding of initializing the nav header then the TextView and edit with results.

Edit

Here is what I did to make it work.
I added

```<code>        uemail = findViewById<View>(R.id.nav_view) as NavigationView
    navHead = uemail.getHeaderView(0)
    tvEmail = navHead.findViewById(R.id.userEmail) as TextView
    tvDisplayName = navHead.findViewById(R.id.userName) as TextView
    tvEmail.text = mUser?.email
    tvDisplayName.text = mUser?.displayName
</code>```

I placed that inside of a function that I called inside of both onCreate and onStart. If I didn't it would only populate after signing in or not at all. This way it populates the correct data and all the time. I found it has something to do with after Android Studio uses a recyclerview for the nav view after 23.1 or something like that.

Body:
I have an app that makes user sign in with Firebase if they are not already signed in. If user signs in their user profile info shows properly. Upon closing the app and reopening the user name and email does not set and goes to my defaulted text. But if I sign out and back in it will show. I feel like it has something to do with updating ui but stuck.

I can post code after my lunch break is over if needed

update with code

This is the relevent code in MainActivity this is where I check if user is logged in if so allow them to go from there if not to start signin activity.

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

val TAG = "MainActivity"

var mAuth: FirebaseAuth? = null
var mUser: FirebaseUser? = null
var userEmailTV: TextView? = null
var userDispNameTV: TextView? = null
val RC_SIGN_IN = 123

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    val toggle = ActionBarDrawerToggle(
            this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
    drawer_layout.addDrawerListener(toggle)
    toggle.syncState()
    nav_view.setNavigationItemSelectedListener(this)

}

 override fun onStart() {
    super.onStart()

    mAuth = FirebaseAuth.getInstance()
    mUser = mAuth?.currentUser

    if (mUser != null) {

        userEmailTV = findViewById<View>(R.id.userEmail) as TextView?
        userEmailTV?.text = mUser?.email
        userDispNameTV = findViewById<View>(R.id.userName) as TextView?
        userDispNameTV?.text = mUser?.displayName

        Log.i(TAG, "User Display Name : ${mUser?.displayName}")
        Log.i(TAG, "Users Email :  ${mUser?.email}")

    } else {
        startActivityForResult(
                // Get an instance of AuthUI based on the default app
                AuthUI.getInstance().createSignInIntentBuilder().build(),
                RC_SIGN_IN)
    }

}

This is the layout info that holds the user profile info inside the navigation drawer

 <TextView
    android:id="@+id/userName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"
    android:text="Username"/>

<TextView
    android:id="@+id/userEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="youremail@something.com"/>

Body:
My theory after much trial and error and research is..... that this problem is not due to the TextView being initialized in the wrong spot as others thought in the comments above but.  Due to the fact that the navigation header view has not had time to inflate. I will work on coding of initializing the nav header then the TextView and edit with results.

Edit

Here is what I did to make it work.
I added

        uemail = findViewById<View>(R.id.nav_view) as NavigationView
    navHead = uemail.getHeaderView(0)
    tvEmail = navHead.findViewById(R.id.userEmail) as TextView
    tvDisplayName = navHead.findViewById(R.id.userName) as TextView
    tvEmail.text = mUser?.email
    tvDisplayName.text = mUser?.displayName

I placed that inside of a function that I called inside of both onCreate and onStart. If I didn't it would only populate after signing in or not at all. This way it populates the correct data and all the time. I found it has something to do with after Android Studio uses a recyclerview for the nav view after 23.1 or something like that.


问:
Pandas cannot plot timeseries imported from Excel
This is my DataFrame obtained importing from an Excel .xls

```<code>    0   1
664     2017-12-07 19:08:54     1.1377
665     2017-12-07 19:10:31     1.1374
666     2017-12-07 19:12:17     1.1377
667     2017-12-07 19:13:28     1.1377
668     2017-12-07 19:15:25     1.1379
</code>```

I think is correclty typed

```<code>0    datetime64[ns]
1           float64
dtype: object
</code>```

However it does not plot with ax = _df.plot() because of some error. Any idea why?
This is my first hour in Pandas, sorry if it's classic question, but I saw only not relevant answers on this ValueError: ordinal must be >= 1

Thanks for your inputs

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-24-ca306a836171> in <module>()
----> 1 ax = _df.plot()

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
   2671                           fontsize=fontsize, colormap=colormap, table=table,
   2672                           yerr=yerr, xerr=xerr, secondary_y=secondary_y,
-> 2673                           sort_columns=sort_columns, **kwds)
   2674     __call__.__doc__ = plot_frame.__doc__
   2675

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
   1898                  yerr=yerr, xerr=xerr,
   1899                  secondary_y=secondary_y, sort_columns=sort_columns,
-> 1900                  **kwds)
   1901
   1902

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in _plot(data, x, y, subplots, ax, kind, **kwds)
   1725         plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
   1726
-> 1727     plot_obj.generate()
   1728     plot_obj.draw()
   1729     return plot_obj.result

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in generate(self)
    258
    259         for ax in self.axes:
--> 260             self._post_plot_logic_common(ax, self.data)
    261             self._post_plot_logic(ax, self.data)
    262

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in _post_plot_logic_common(self, ax, data)
    393             self._apply_axis_properties(ax.xaxis, rot=self.rot,
    394                                         fontsize=self.fontsize)
--> 395             self._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)
    396
    397             if hasattr(ax, 'right_ax'):

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in _apply_axis_properties(self, axis, rot, fontsize)
    466
    467     def _apply_axis_properties(self, axis, rot=None, fontsize=None):
--> 468         labels = axis.get_majorticklabels() + axis.get_minorticklabels()
    469         for label in labels:
    470             if rot is not None:

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in get_majorticklabels(self)
   1189     def get_majorticklabels(self):
   1190         'Return a list of Text instances for the major ticklabels'
-> 1191         ticks = self.get_major_ticks()
   1192         labels1 = [tick.label1 for tick in ticks if tick.label1On]
   1193         labels2 = [tick.label2 for tick in ticks if tick.label2On]

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in get_major_ticks(self, numticks)
   1318         'get the tick instances; grow as necessary'
   1319         if numticks is None:
-> 1320             numticks = len(self.get_major_locator()())
   1321         if len(self.majorTicks) < numticks:
   1322             # update the new tick label properties from the old

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in __call__(self)
    984     def __call__(self):
    985         'Return the locations of the ticks'
--> 986         self.refresh()
    987         return self._locator()
    988

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in refresh(self)
   1004     def refresh(self):
   1005         'Refresh internal information based on current limits.'
-> 1006         dmin, dmax = self.viewlim_to_dt()
   1007         self._locator = self.get_locator(dmin, dmax)
   1008

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
    761             vmin, vmax = vmax, vmin
    762
--> 763         return num2date(vmin, self.tz), num2date(vmax, self.tz)
    764
    765     def _get_unit(self):

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in num2date(x, tz)
    399         tz = _get_rc_timezone()
    400     if not cbook.iterable(x):
--> 401         return _from_ordinalf(x, tz)
    402     else:
    403         x = np.asarray(x)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in _from_ordinalf(x, tz)
    252
    253     ix = int(x)
--> 254     dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
    255
    256     remainder = float(x) - ix

ValueError: ordinal must be >= 1

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj)
    330                 pass
    331             else:
--> 332                 return printer(obj)
    333             # Finally look for special method names
    334             method = get_real_method(obj, self.print_method)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
    235
    236     if 'png' in formats:
--> 237         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    238     if 'retina' in formats or 'png2x' in formats:
    239         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    119
    120     bytes_io = BytesIO()
--> 121     fig.canvas.print_figure(bytes_io, **kw)
    122     data = bytes_io.getvalue()
    123     if fmt == 'svg':

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2198                     orientation=orientation,
   2199                     dryrun=True,
-> 2200                     **kwargs)
   2201                 renderer = self.figure._cachedRenderer
   2202                 bbox_inches = self.figure.get_tightbbox(renderer)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    543
    544     def print_png(self, filename_or_obj, *args, **kwargs):
--> 545         FigureCanvasAgg.draw(self)
    546         renderer = self.get_renderer()
    547         original_dpi = renderer.dpi

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    462
    463         try:
--> 464             self.figure.draw(self.renderer)
    465         finally:
    466             RendererAgg.lock.release()

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     61     def draw_wrapper(artist, renderer, *args, **kwargs):
     62         before(artist, renderer)
---> 63         draw(artist, renderer, *args, **kwargs)
     64         after(artist, renderer)
     65

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/figure.py in draw(self, renderer)
   1142
   1143             mimage._draw_list_compositing_images(
-> 1144                 renderer, self, dsu, self.suppressComposite)
   1145
   1146             renderer.close_group('figure')

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, dsu, suppress_composite)
    137     if not_composite or not has_images:
    138         for zorder, a in dsu:
--> 139             a.draw(renderer)
    140     else:
    141         # Composite any adjacent images together

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     61     def draw_wrapper(artist, renderer, *args, **kwargs):
     62         before(artist, renderer)
---> 63         draw(artist, renderer, *args, **kwargs)
     64         after(artist, renderer)
     65

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2424             renderer.stop_rasterizing()
   2425
-> 2426         mimage._draw_list_compositing_images(renderer, self, dsu)
   2427
   2428         renderer.close_group('axes')

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, dsu, suppress_composite)
    137     if not_composite or not has_images:
    138         for zorder, a in dsu:
--> 139             a.draw(renderer)
    140     else:
    141         # Composite any adjacent images together

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     61     def draw_wrapper(artist, renderer, *args, **kwargs):
     62         before(artist, renderer)
---> 63         draw(artist, renderer, *args, **kwargs)
     64         after(artist, renderer)
     65

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1134         renderer.open_group(__name__)
   1135
-> 1136         ticks_to_draw = self._update_ticks(renderer)
   1137         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1138                                                                 renderer)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in _update_ticks(self, renderer)
    967
    968         interval = self.get_view_interval()
--> 969         tick_tups = [t for t in self.iter_ticks()]
    970         if self._smart_bounds:
    971             # handle inverted limits

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in <listcomp>(.0)
    967
    968         interval = self.get_view_interval()
--> 969         tick_tups = [t for t in self.iter_ticks()]
    970         if self._smart_bounds:
    971             # handle inverted limits

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in iter_ticks(self)
    910         Iterate through all of the major and minor ticks.
    911         """
--> 912         majorLocs = self.major.locator()
    913         majorTicks = self.get_major_ticks(len(majorLocs))
    914         self.major.formatter.set_locs(majorLocs)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in __call__(self)
    984     def __call__(self):
    985         'Return the locations of the ticks'
--> 986         self.refresh()
    987         return self._locator()
    988

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in refresh(self)
   1004     def refresh(self):
   1005         'Refresh internal information based on current limits.'
-> 1006         dmin, dmax = self.viewlim_to_dt()
   1007         self._locator = self.get_locator(dmin, dmax)
   1008

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
    761             vmin, vmax = vmax, vmin
    762
--> 763         return num2date(vmin, self.tz), num2date(vmax, self.tz)
    764
    765     def _get_unit(self):

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in num2date(x, tz)
    399         tz = _get_rc_timezone()
    400     if not cbook.iterable(x):
--> 401         return _from_ordinalf(x, tz)
    402     else:
    403         x = np.asarray(x)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in _from_ordinalf(x, tz)
    252
    253     ix = int(x)
--> 254     dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
    255
    256     remainder = float(x) - ix

ValueError: ordinal must be >= 1

<matplotlib.figure.Figure at 0x118f1e978>
</code>```

答:
You probably want to plot column 1 agains column 0, i.e. the numbers against the dates? This would be done via

```<code>df.plot(x=0,y=1)
</code>```

Your columns are unnamed. So you may also name them and reset the index to something useful (or as below, not so useful ;-))

```<code>df.columns = ["0", "1"]
df = df.set_index("0")
df.plot()
</code>```

Both should give you a plot like the following:

Body:
This is my DataFrame obtained importing from an Excel .xls

    0   1
664     2017-12-07 19:08:54     1.1377
665     2017-12-07 19:10:31     1.1374
666     2017-12-07 19:12:17     1.1377
667     2017-12-07 19:13:28     1.1377
668     2017-12-07 19:15:25     1.1379

I think is correclty typed

0    datetime64[ns]
1           float64
dtype: object

However it does not plot with ax = _df.plot() because of some error. Any idea why?
This is my first hour in Pandas, sorry if it's classic question, but I saw only not relevant answers on this ValueError: ordinal must be >= 1

Thanks for your inputs

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-24-ca306a836171> in <module>()
----> 1 ax = _df.plot()

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
   2671                           fontsize=fontsize, colormap=colormap, table=table,
   2672                           yerr=yerr, xerr=xerr, secondary_y=secondary_y,
-> 2673                           sort_columns=sort_columns, **kwds)
   2674     __call__.__doc__ = plot_frame.__doc__
   2675

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
   1898                  yerr=yerr, xerr=xerr,
   1899                  secondary_y=secondary_y, sort_columns=sort_columns,
-> 1900                  **kwds)
   1901
   1902

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in _plot(data, x, y, subplots, ax, kind, **kwds)
   1725         plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
   1726
-> 1727     plot_obj.generate()
   1728     plot_obj.draw()
   1729     return plot_obj.result

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in generate(self)
    258
    259         for ax in self.axes:
--> 260             self._post_plot_logic_common(ax, self.data)
    261             self._post_plot_logic(ax, self.data)
    262

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in _post_plot_logic_common(self, ax, data)
    393             self._apply_axis_properties(ax.xaxis, rot=self.rot,
    394                                         fontsize=self.fontsize)
--> 395             self._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)
    396
    397             if hasattr(ax, 'right_ax'):

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/plotting/_core.py in _apply_axis_properties(self, axis, rot, fontsize)
    466
    467     def _apply_axis_properties(self, axis, rot=None, fontsize=None):
--> 468         labels = axis.get_majorticklabels() + axis.get_minorticklabels()
    469         for label in labels:
    470             if rot is not None:

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in get_majorticklabels(self)
   1189     def get_majorticklabels(self):
   1190         'Return a list of Text instances for the major ticklabels'
-> 1191         ticks = self.get_major_ticks()
   1192         labels1 = [tick.label1 for tick in ticks if tick.label1On]
   1193         labels2 = [tick.label2 for tick in ticks if tick.label2On]

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in get_major_ticks(self, numticks)
   1318         'get the tick instances; grow as necessary'
   1319         if numticks is None:
-> 1320             numticks = len(self.get_major_locator()())
   1321         if len(self.majorTicks) < numticks:
   1322             # update the new tick label properties from the old

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in __call__(self)
    984     def __call__(self):
    985         'Return the locations of the ticks'
--> 986         self.refresh()
    987         return self._locator()
    988

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in refresh(self)
   1004     def refresh(self):
   1005         'Refresh internal information based on current limits.'
-> 1006         dmin, dmax = self.viewlim_to_dt()
   1007         self._locator = self.get_locator(dmin, dmax)
   1008

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
    761             vmin, vmax = vmax, vmin
    762
--> 763         return num2date(vmin, self.tz), num2date(vmax, self.tz)
    764
    765     def _get_unit(self):

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in num2date(x, tz)
    399         tz = _get_rc_timezone()
    400     if not cbook.iterable(x):
--> 401         return _from_ordinalf(x, tz)
    402     else:
    403         x = np.asarray(x)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in _from_ordinalf(x, tz)
    252
    253     ix = int(x)
--> 254     dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
    255
    256     remainder = float(x) - ix

ValueError: ordinal must be >= 1

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj)
    330                 pass
    331             else:
--> 332                 return printer(obj)
    333             # Finally look for special method names
    334             method = get_real_method(obj, self.print_method)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
    235
    236     if 'png' in formats:
--> 237         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    238     if 'retina' in formats or 'png2x' in formats:
    239         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    119
    120     bytes_io = BytesIO()
--> 121     fig.canvas.print_figure(bytes_io, **kw)
    122     data = bytes_io.getvalue()
    123     if fmt == 'svg':

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2198                     orientation=orientation,
   2199                     dryrun=True,
-> 2200                     **kwargs)
   2201                 renderer = self.figure._cachedRenderer
   2202                 bbox_inches = self.figure.get_tightbbox(renderer)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    543
    544     def print_png(self, filename_or_obj, *args, **kwargs):
--> 545         FigureCanvasAgg.draw(self)
    546         renderer = self.get_renderer()
    547         original_dpi = renderer.dpi

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    462
    463         try:
--> 464             self.figure.draw(self.renderer)
    465         finally:
    466             RendererAgg.lock.release()

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     61     def draw_wrapper(artist, renderer, *args, **kwargs):
     62         before(artist, renderer)
---> 63         draw(artist, renderer, *args, **kwargs)
     64         after(artist, renderer)
     65

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/figure.py in draw(self, renderer)
   1142
   1143             mimage._draw_list_compositing_images(
-> 1144                 renderer, self, dsu, self.suppressComposite)
   1145
   1146             renderer.close_group('figure')

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, dsu, suppress_composite)
    137     if not_composite or not has_images:
    138         for zorder, a in dsu:
--> 139             a.draw(renderer)
    140     else:
    141         # Composite any adjacent images together

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     61     def draw_wrapper(artist, renderer, *args, **kwargs):
     62         before(artist, renderer)
---> 63         draw(artist, renderer, *args, **kwargs)
     64         after(artist, renderer)
     65

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2424             renderer.stop_rasterizing()
   2425
-> 2426         mimage._draw_list_compositing_images(renderer, self, dsu)
   2427
   2428         renderer.close_group('axes')

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, dsu, suppress_composite)
    137     if not_composite or not has_images:
    138         for zorder, a in dsu:
--> 139             a.draw(renderer)
    140     else:
    141         # Composite any adjacent images together

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     61     def draw_wrapper(artist, renderer, *args, **kwargs):
     62         before(artist, renderer)
---> 63         draw(artist, renderer, *args, **kwargs)
     64         after(artist, renderer)
     65

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1134         renderer.open_group(__name__)
   1135
-> 1136         ticks_to_draw = self._update_ticks(renderer)
   1137         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1138                                                                 renderer)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in _update_ticks(self, renderer)
    967
    968         interval = self.get_view_interval()
--> 969         tick_tups = [t for t in self.iter_ticks()]
    970         if self._smart_bounds:
    971             # handle inverted limits

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in <listcomp>(.0)
    967
    968         interval = self.get_view_interval()
--> 969         tick_tups = [t for t in self.iter_ticks()]
    970         if self._smart_bounds:
    971             # handle inverted limits

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/axis.py in iter_ticks(self)
    910         Iterate through all of the major and minor ticks.
    911         """
--> 912         majorLocs = self.major.locator()
    913         majorTicks = self.get_major_ticks(len(majorLocs))
    914         self.major.formatter.set_locs(majorLocs)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in __call__(self)
    984     def __call__(self):
    985         'Return the locations of the ticks'
--> 986         self.refresh()
    987         return self._locator()
    988

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in refresh(self)
   1004     def refresh(self):
   1005         'Refresh internal information based on current limits.'
-> 1006         dmin, dmax = self.viewlim_to_dt()
   1007         self._locator = self.get_locator(dmin, dmax)
   1008

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
    761             vmin, vmax = vmax, vmin
    762
--> 763         return num2date(vmin, self.tz), num2date(vmax, self.tz)
    764
    765     def _get_unit(self):

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in num2date(x, tz)
    399         tz = _get_rc_timezone()
    400     if not cbook.iterable(x):
--> 401         return _from_ordinalf(x, tz)
    402     else:
    403         x = np.asarray(x)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/dates.py in _from_ordinalf(x, tz)
    252
    253     ix = int(x)
--> 254     dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
    255
    256     remainder = float(x) - ix

ValueError: ordinal must be >= 1

<matplotlib.figure.Figure at 0x118f1e978>

Body:
You probably want to plot column 1 agains column 0, i.e. the numbers against the dates? This would be done via

df.plot(x=0,y=1)

Your columns are unnamed. So you may also name them and reset the index to something useful (or as below, not so useful ;-))

df.columns = ["0", "1"]
df = df.set_index("0")
df.plot()

Both should give you a plot like the following:


问:
Apple XCode on multiple machines (how to take my project with me?)
I mainly develop iOS applications on a Mac desktop, but sometimes I travel with a MacBook Air laptop and I often need to continue working on an app while on the road.

Of course, it's possible to just scp the files to my laptop, work on it, then scp it back to the desktop, or use a thumb drive. But I have to believe that thousands of others have a similar need.  Is there a simple way to share the source control and just check in/out while on the road?

What are the best practices for smooth, single-developer track development on multiple devices?

答:
I'm not sure this question belongs here, but hey, I ask it myself, so these are my practices. I won't call it "best" practices, just the stuff that I tried over the years:

Git

Use a git repository. I guess you're already using it, if not, create a repository (in Bitbucket you can have private repos for free). Do it even if you use something else to sync your computers.

There are many ways of using git to keep your desktop and laptop synchronised. When it's not easy to perform proper commits (i.e. you're in the middle of a big change and you don't want to just commit everything under a non-sense commit log) you can write a throw away commit using a predetermined message like ** SYNC **, then push it to your remote.

In your laptop, pull and soft reset to have the changes as they were before committing: git reset HEAD^.

When you're back to your desktop, do a hard reset of the last commit git reset --hard HEAD^ and pull the changes.

Not the best solution in my experience: the transition desktop/laptop should be fast and effortless. Thinking about what to commit and how just because you need to change the machine is a pain.

Resilio Sync

Synchronize several folders between desktop and laptop with Bittorrent Resilio Sync (it's possible to configure it to use only LAN if you're paranoid about security).

It worked for a while, very well, but somehow it broke and I didn't want to investigate the cause because I suspected it'll break again later.

Dropbox

Synchronize both computers using Dropbox, when I'm lazy. It works fine. If you trust Dropbox anyway.

Same thing with other cloud providers (except iCloud that is painfully slow).

SSD Card

Work directly in an SSD card. It's fast enough; just make sure you don't write the builds to the card. You need a card reader in both computers, obviously. Not a long term solution.

Mac Apps

Dedicated mac apps that sync folders between machines. None of them worked flawlessly. Some were too complicated, or unmaintained, or horrible windows ports,  etc. I'd buy a simple one that works and communicates clearly what it does under the hood.

Rsync

Use rsync to keep the project folder synchronised in both computers.

Right now I use the rsync solution on top of macOS shared folders (you can use it over SSH if you prefer).

I have a couple of shell scripts per project inside the project folder:

```<code>project-name->laptop.sh
project-name->desktop.sh
</code>```

Where "laptop" and "desktop" are my machine names. When I need to use the laptop I just mount the shared folder (usually I just need to open the laptop) and run project-name->laptop.sh. When I'm back, I'll do the opposite, I run project-name->desktop.sh. Simple and easy. You can have each script in the corresponding machine only, to avoid mistakes.

Example:

```<code>PROJECT_DIR=/Volumes/julian/path/to/project

if [ ! -d $PROJECT_DIR ] ; then
    echo "Mount $PROJECT_DIR first."
    exit 10
fi

if [ ! -x ./sync.sh ] ; then
    echo "Must run from /local/path/project directory"
    exit 11
fi

./sync.sh $PROJECT_DIR project-name $@
</code>```

And sync.sh is the same for all projects, something like:

```<code>#!/bin/sh
#
# sync.sh <project-folder> [-no]
#
SOURCE_DIR=$1 && shift
TARGET_DIR=$1 && shift

function usage {
    echo $0 '<project> [-no]'
}

if [ "$SOURCE_DIR" == "" ] ; then
    echo 'Missing source'
    usage
    exit 1
fi

if [ "$TARGET_DIR" == "" ] ; then
    echo 'Missing target'
    usage
    exit 2
fi

rsync $@ -va --delete         \
      --exclude='*.pyc'       \
      --exclude='*.db'       \
      --exclude='__pycache__' \
      --exclude='.DS_Store'   \
      --exclude='._*'         \
      ${SOURCE_DIR}/ \
      ${TARGET_DIR}/
</code>```

I have used some other solution that I have forgotten already. For me rsync is the most easy and stable alternative.

Body:
I'm not sure this question belongs here, but hey, I ask it myself, so these are my practices. I won't call it "best" practices, just the stuff that I tried over the years:

Git

Use a git repository. I guess you're already using it, if not, create a repository (in Bitbucket you can have private repos for free). Do it even if you use something else to sync your computers.

There are many ways of using git to keep your desktop and laptop synchronised. When it's not easy to perform proper commits (i.e. you're in the middle of a big change and you don't want to just commit everything under a non-sense commit log) you can write a throw away commit using a predetermined message like ** SYNC **, then push it to your remote.

In your laptop, pull and soft reset to have the changes as they were before committing: git reset HEAD^.

When you're back to your desktop, do a hard reset of the last commit git reset --hard HEAD^ and pull the changes.

Not the best solution in my experience: the transition desktop/laptop should be fast and effortless. Thinking about what to commit and how just because you need to change the machine is a pain.

Resilio Sync

Synchronize several folders between desktop and laptop with Bittorrent Resilio Sync (it's possible to configure it to use only LAN if you're paranoid about security).

It worked for a while, very well, but somehow it broke and I didn't want to investigate the cause because I suspected it'll break again later.

Dropbox

Synchronize both computers using Dropbox, when I'm lazy. It works fine. If you trust Dropbox anyway.

Same thing with other cloud providers (except iCloud that is painfully slow).

SSD Card

Work directly in an SSD card. It's fast enough; just make sure you don't write the builds to the card. You need a card reader in both computers, obviously. Not a long term solution.

Mac Apps

Dedicated mac apps that sync folders between machines. None of them worked flawlessly. Some were too complicated, or unmaintained, or horrible windows ports,  etc. I'd buy a simple one that works and communicates clearly what it does under the hood.

Rsync

Use rsync to keep the project folder synchronised in both computers.

Right now I use the rsync solution on top of macOS shared folders (you can use it over SSH if you prefer).

I have a couple of shell scripts per project inside the project folder:

project-name->laptop.sh
project-name->desktop.sh

Where "laptop" and "desktop" are my machine names. When I need to use the laptop I just mount the shared folder (usually I just need to open the laptop) and run project-name->laptop.sh. When I'm back, I'll do the opposite, I run project-name->desktop.sh. Simple and easy. You can have each script in the corresponding machine only, to avoid mistakes.

Example:

PROJECT_DIR=/Volumes/julian/path/to/project

if [ ! -d $PROJECT_DIR ] ; then
    echo "Mount $PROJECT_DIR first."
    exit 10
fi

if [ ! -x ./sync.sh ] ; then
    echo "Must run from /local/path/project directory"
    exit 11
fi

./sync.sh $PROJECT_DIR project-name $@

And sync.sh is the same for all projects, something like:

#!/bin/sh
#
# sync.sh <project-folder> [-no]
#
SOURCE_DIR=$1 && shift
TARGET_DIR=$1 && shift

function usage {
    echo $0 '<project> [-no]'
}

if [ "$SOURCE_DIR" == "" ] ; then
    echo 'Missing source'
    usage
    exit 1
fi

if [ "$TARGET_DIR" == "" ] ; then
    echo 'Missing target'
    usage
    exit 2
fi

rsync $@ -va --delete         \
      --exclude='*.pyc'       \
      --exclude='*.db'       \
      --exclude='__pycache__' \
      --exclude='.DS_Store'   \
      --exclude='._*'         \
      ${SOURCE_DIR}/ \
      ${TARGET_DIR}/

I have used some other solution that I have forgotten already. For me rsync is the most easy and stable alternative.


问:
Is it possible to have the "IF" on a "select" statement or using "Case"?
I have an IF statement that basically gives me concatenation of addresses if value for them is not null. as see below :

```<code>IF @Address1 IS NOT NULL
BEGIN
    IF @Address2 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+@Address2
        ELSE SET @TotalAddress=@Address1;
    IF @Address3 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')
    IF @Address4 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')+CHAR(13)+ISNULL(@Address4, '')
END
</code>```

I was wondering if I can have my code in select statement directly and grab address1,2 and 3 without creating a variable.

答:
Here is another way using IIF():

```<code>SELECT IIF(@Address1 IS NULL, '', @Address1 + CHAR(13))+
       IIF(@Address2 IS NULL, '', @Address2 + CHAR(13))+
       IIF(@Address3 IS NULL, '', @Address3 + CHAR(13))+
       IIF(@Address4 IS NULL, '', @Address4 + CHAR(13)) AS Result
</code>```

Body:
I have an IF statement that basically gives me concatenation of addresses if value for them is not null. as see below :

IF @Address1 IS NOT NULL
BEGIN
    IF @Address2 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+@Address2
        ELSE SET @TotalAddress=@Address1;
    IF @Address3 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')
    IF @Address4 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')+CHAR(13)+ISNULL(@Address4, '')
END

I was wondering if I can have my code in select statement directly and grab address1,2 and 3 without creating a variable.

Body:
Here is another way using IIF():

SELECT IIF(@Address1 IS NULL, '', @Address1 + CHAR(13))+
       IIF(@Address2 IS NULL, '', @Address2 + CHAR(13))+
       IIF(@Address3 IS NULL, '', @Address3 + CHAR(13))+
       IIF(@Address4 IS NULL, '', @Address4 + CHAR(13)) AS Result


问:
Mercurial changegroup hook is being passed wrong HG_URL
I've setup a simple changegroup hook for my Mercurial repositories to email the set of changes to interested users. I'd like to use a single script for every repository I manage, and I would also like to identify the repository the changegroup came from. According to the Mercurial Hooks documentation, the environment variable HG_URL is available for this purpose. However, I am not getting what I'm expecting from this variable:

expected:

```<code>https://repo01/hg/project
</code>```

actual:

```<code>remote:https::rnideffer
</code>```

Why is this the URL, and how do I get what I expected into the changegroup hook?

答:
The changegroup hook can't always tell the remote URL being used.  From the Hooks chapter of the Mercurial Book:

When possible, Mercurial will tell a
  hook the location of the “far side” of
  an activity that transfers changeset
  data between repositories. This is
  provided by Mercurial in a Python
  parameter named url, or an environment
  variable named HG_URL. No comments

This information is not always known.
  If a hook is invoked in a repository
  that is being served via http or ssh,
  Mercurial cannot tell where the remote
  repository is, but it may know where
  the client is connecting from. In such
  cases, the URL will take one of the
  following forms: No comments

remote:ssh:1.2.3.4—remote ssh client,
  at the IP address 1.2.3.4. No comments

remote:http:1.2.3.4—remote http
  client, at the IP address 1.2.3.4. If
  the client is using SSL, this will be
  of the form remote:https:1.2.3.4. No
  comments

So you're being told they're pushing via https from a machine named rnideffer.

Have you considered using the notify extension?  It ships with mercurial, does pretty much exactly what you're describing, and can be provided with the URL prefix necessary to turn repo names into the URLs you want.

Body:
I've setup a simple changegroup hook for my Mercurial repositories to email the set of changes to interested users. I'd like to use a single script for every repository I manage, and I would also like to identify the repository the changegroup came from. According to the Mercurial Hooks documentation, the environment variable HG_URL is available for this purpose. However, I am not getting what I'm expecting from this variable:

expected:

https://repo01/hg/project

actual:

remote:https::rnideffer

Why is this the URL, and how do I get what I expected into the changegroup hook?


问:
Working with Multiple Nuget Projects in one Solution
I have 2 projects: A & B that I want to publish as NuGet Packages but I don't know how to develop efficiently in Visual Studio.

```<code>Solution 1
   Project A
   Project B - references Project A as NuGet reference
</code>```

When I make a change to Project A that is needed in Project B do I have to publish Project A?  Is there a way to get the project reference functionality during development?  Maybe Project B shouldn't reference Project A via NuGet?

There must be a good way to handle this situation, no?  I've reviewed the NuGet docs but I couldn't find anything.  There must be docs/blogs/SO posts to read more about this... I'm struggling to come up w/ the right keywords.

答:
You might want to look at this extension: NuGet Reference Switcher for Visual Studio 2017

This allows you to switch between NuGet packages and project references during development.

ContentLicense: CC BY-SA 4.0

Body:
I have 2 projects: A & B that I want to publish as NuGet Packages but I don't know how to develop efficiently in Visual Studio.

Solution 1
   Project A
   Project B - references Project A as NuGet reference

When I make a change to Project A that is needed in Project B do I have to publish Project A?  Is there a way to get the project reference functionality during development?  Maybe Project B shouldn't reference Project A via NuGet?

There must be a good way to handle this situation, no?  I've reviewed the NuGet docs but I couldn't find anything.  There must be docs/blogs/SO posts to read more about this... I'm struggling to come up w/ the right keywords.


问:
Building an object using async ajax calls
I need to return a custom object that relies on multiple async jquery ajax calls.

Sample code below:

```<code>function BuildMyObject() {
    var bp = null;
    var accountId = getAccountId();
    var signature = getSignature();
    var transactionType = getTransactionType();
    var mode = getMode();
    var merchantIdentifier = getMerchantIdentifier();
    jQuery.when(accountId, signature, transactionType, mode, merchantIdentifier).done(function(rAcctId,
        rSig,
        rTransType,
        rMode,
        rMerchId) {
        bp = new MyObject(
            rAcctId[0],
            rSig[0],
            rTransType[0],
            rMode[0],
            rMerchId[0]);
    });
    return bp;
}
</code>```

Now, this returns null; as the return statement is firing before the async calls finish.  Is there a way to wait untill all the calls are finished before returning the object?  If i set the ajax calls to synchronious, it works; but I'd like to avoid that.

答:
you can work with Promises or callbacks for scenarios  of async  functions

//callback example
function BuildMyObject(callback) {
    var bp = null;
    var accountId = getAccountId();
    var signature = getSignature();
    var transactionType = getTransactionType();
    var mode = getMode();
    var merchantIdentifier = getMerchantIdentifier();
    jQuery.when(accountId, signature, transactionType, mode, merchantIdentifier).done(function(rAcctId,
        rSig,
        rTransType,
        rMode,
        rMerchId) {
        bp = new MyObject(
            rAcctId[0],
            rSig[0],
            rTransType[0],
            rMode[0],
            rMerchId[0]);
            )
        callback(bp)

    });

}

//or with promise

function BuildMyObject() {
    return new Promise((resolve,reject) =>{
        var bp = null;
        var accountId = getAccountId();
        var signature = getSignature();
        var transactionType = getTransactionType();
        var mode = getMode();
        var merchantIdentifier = getMerchantIdentifier();
        jQuery.when(accountId, signature, transactionType, mode, merchantIdentifier).done(function(rAcctId,
            rSig,
            rTransType,
            rMode,
            rMerchId) {
            bp = new MyObject(
                rAcctId[0],
                rSig[0],
                rTransType[0],
                rMode[0],
                rMerchId[0]);
           )
           resolve(bp)
        });

    })

}

BuildMyObject()
.then((bp) =>{
    //do somthing with bp
})```

Body:
I need to return a custom object that relies on multiple async jquery ajax calls.

Sample code below:

function BuildMyObject() {
    var bp = null;
    var accountId = getAccountId();
    var signature = getSignature();
    var transactionType = getTransactionType();
    var mode = getMode();
    var merchantIdentifier = getMerchantIdentifier();
    jQuery.when(accountId, signature, transactionType, mode, merchantIdentifier).done(function(rAcctId,
        rSig,
        rTransType,
        rMode,
        rMerchId) {
        bp = new MyObject(
            rAcctId[0],
            rSig[0],
            rTransType[0],
            rMode[0],
            rMerchId[0]);
    });
    return bp;
}

Now, this returns null; as the return statement is firing before the async calls finish.  Is there a way to wait untill all the calls are finished before returning the object?  If i set the ajax calls to synchronious, it works; but I'd like to avoid that.


问:
Detect if HTML5 video volume property is read-only?
I have a mute button that sets my video volume to 0:

```<code>video.volume = 0;
</code>```

If this isn't supported I'd like to hide the mute button. I can use user-agent detection, but that is less than ideal. Does anyone know of a way to check if this property is read-only?

Thanks,

Tim

答:
to mute use .muted. The old volume will be remembered and it works everywhere.

```<code>video.muted = true;
</code>```

Body:
I have a mute button that sets my video volume to 0:

video.volume = 0;

If this isn't supported I'd like to hide the mute button. I can use user-agent detection, but that is less than ideal. Does anyone know of a way to check if this property is read-only?

Thanks,

Tim

Body:
to mute use .muted. The old volume will be remembered and it works everywhere.

video.muted = true;


问:
PySpark: TypeError: StructType can not accept object in type <type 'unicode'> or <type 'str'>
I am reading data from a CSV file and then creating a DataFrame. But when I try to access the data in the DataFrame I get TypeError.

```<code>fields = [StructField(field_name, StringType(), True) for field_name in schema.split(',')]
schema = StructType(fields)

input_dataframe = sql_context.createDataFrame(input_data_1, schema)

print input_dataframe.filter(input_dataframe.diagnosis_code == '11').count()
</code>```

Both 'unicode' and 'str' are not working with Spark DataFrame. I get the below TypeError:

TypeError: StructType can not accept object in type
TypeError: StructType can not accept object in type

I tried encoding in 'utf-8' as below but still get the error but now complaining about TypeError with 'str':

```<code>input_data_2 = input_data_1.map(lambda x: x.encode("utf-8"))
input_dataframe = sql_context.createDataFrame(input_data_2, schema)

print input_dataframe.filter(input_dataframe.diagnosis_code == '410.11').count()
</code>```

I also tried parsing the CSV directly as utf-8 or unicode using the param use_unicode=True/False

答:
Reading between the lines. You are

reading data from a CSV file

and get

```<code>TypeError: StructType can not accept object in type <type 'unicode'>
</code>```

This happens because you pass a string not an object compatible with struct. Probably you pass data like:

```<code>input_data_1 = sc.parallelize(["1,foo,2", "2,bar,3"])
</code>```

and schema

```<code>schema = "x,y,z"

fields = [StructField(field_name, StringType(), True) for field_name in schema.split(',')]
schema = StructType(fields)
</code>```

and you expect Spark to figure things out. But it doesn't work that way. You could

```<code>input_dataframe = sqlContext.createDataFrame(input_data_1.map(lambda s: s.split(",")), schema)
</code>```

but honestly just use Spark csv reader:

```<code>spark.read.schema(schema).csv("/path/to/file")
</code>```

Body:
I am reading data from a CSV file and then creating a DataFrame. But when I try to access the data in the DataFrame I get TypeError.

fields = [StructField(field_name, StringType(), True) for field_name in schema.split(',')]
schema = StructType(fields)

input_dataframe = sql_context.createDataFrame(input_data_1, schema)

print input_dataframe.filter(input_dataframe.diagnosis_code == '11').count()

Both 'unicode' and 'str' are not working with Spark DataFrame. I get the below TypeError:

TypeError: StructType can not accept object in type
TypeError: StructType can not accept object in type

I tried encoding in 'utf-8' as below but still get the error but now complaining about TypeError with 'str':

input_data_2 = input_data_1.map(lambda x: x.encode("utf-8"))
input_dataframe = sql_context.createDataFrame(input_data_2, schema)

print input_dataframe.filter(input_dataframe.diagnosis_code == '410.11').count()

I also tried parsing the CSV directly as utf-8 or unicode using the param use_unicode=True/False

Body:
Reading between the lines. You are

reading data from a CSV file

and get

TypeError: StructType can not accept object in type <type 'unicode'>

This happens because you pass a string not an object compatible with struct. Probably you pass data like:

input_data_1 = sc.parallelize(["1,foo,2", "2,bar,3"])

and schema

schema = "x,y,z"

fields = [StructField(field_name, StringType(), True) for field_name in schema.split(',')]
schema = StructType(fields)

and you expect Spark to figure things out. But it doesn't work that way. You could

input_dataframe = sqlContext.createDataFrame(input_data_1.map(lambda s: s.split(",")), schema)

but honestly just use Spark csv reader:

spark.read.schema(schema).csv("/path/to/file")


问:
Java StringTemplate Using File From Outside Directory
I have a directory structure like this:

```<code>Templates/
├── Foo/
│   ├── Foo.st
├── Signature.st
</code>```

Here's what the Foo.st looks like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>
    <div id="body">
        <p> Some Text </p>
    </div>
    $Signature()$
</body>
</html>
</code>```

Here's my Java code with StringTemplate:

```<code>STRawGroupDir dir = new STRawGroupDir("Templates", '$', '$');
ST st = dir.getInstanceOf("Foo/Foo");
System.out.println(st.render());
</code>```

But the output is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>
    <div id="body">
        <p> Some Text </p>
    </div>
</body>
</html>
</code>```

How do I get the Foo template to be able to properly reference the signature template?

If I put Signature.st inside the Foo directory then the above code works just fine, but I can't do that as I'll have many templates that will reference the Signature template.

答:
Try:

```<code>...
$/Signature()$
...
</code>```

Template calls are resolved relative to the calling template. Starting a template call with prefix / will make the template call absolute - which is what you expect.

Body:
I have a directory structure like this:

Templates/
├── Foo/
│   ├── Foo.st
├── Signature.st

Here's what the Foo.st looks like:

<?xml version="1.0" encoding="UTF-8"?>

 Some Text

    $Signature()$

Here's my Java code with StringTemplate:

STRawGroupDir dir = new STRawGroupDir("Templates", '$', '$');
ST st = dir.getInstanceOf("Foo/Foo");
System.out.println(st.render());

But the output is:

<?xml version="1.0" encoding="UTF-8"?>

 Some Text

How do I get the Foo template to be able to properly reference the signature template?

If I put Signature.st inside the Foo directory then the above code works just fine, but I can't do that as I'll have many templates that will reference the Signature template.

Body:
Try:

...
$/Signature()$
...

Template calls are resolved relative to the calling template. Starting a template call with prefix / will make the template call absolute - which is what you expect.


问:
Parsing strings at compile-time - if possible
I am trying to make compile time checks over the format of the printf. Here is the code.

```<code>#include <type_traits>
#include <iostream>

template <typename CHAR, typename ...ARGS>
constexpr size_t trace_cond(CHAR fmt, ARGS&&... args) {
   //always needs to pass
   return 1;
}

template <size_t N, typename ...ARGS>
constexpr size_t trace_cond(const char (&fmt)[N], ARGS&&... args) {
   //return parse(fmt) == args;
   return sizeof...(args) != 0;
}

#define TRACE(fmt, ...) { \
   static_assert(trace_cond(fmt, __VA_ARGS__), "Wrong ARGS"); \
   printf(fmt, ##__VA_ARGS__); \
}

int main(int argc, char* argv[]) {
  //working fine
  TRACE("%d %d\n", 2, 3);

  const char* format = "%d %d\n";
  //error
  TRACE(format, 2, 3);
}
</code>```

So when the format is known at compile time I want to have a check(using static_assert) and if it is not known then the check should be not called or always to pass

Obs:

Currently the code is not compiling because const char *format is not declared constexpr

The main should not be change because TRACE macro is used in a large codebase but changes to TRACE are more than welcome

So my question is:
Is there a way to skip static_assert or make it pass when fmt type is const char *

答:
I think you can do what you want by moving the static_assert to the trace_cond

```<code>#include <type_traits>
#include <iostream>

template <size_t C, typename CHAR>
size_t trace_cond(CHAR fmt) {
    //always needs to pass
    return 1;
}

template <typename ...ARGS>
constexpr size_t count_args(ARGS&&... args) {
    return sizeof...(args);
}

template <size_t C, size_t N>
constexpr size_t trace_cond(const char (&fmt)[N]) {
    // TODO, parse fmt and do the needed checks
    static_assert(C == 3, "");
    return 1;
}

#define TRACE(fmt, ...) { \
    trace_cond<count_args(__VA_ARGS__)>(fmt); \
    printf(fmt, ##__VA_ARGS__); \
}

int main(int argc, char* argv[]) {
    // Static check - hard coded to check for 3 arguments
    TRACE("%d %d %d\n", 2, 3, 4);

    const char* format = "%d %d\n";
    // No checks performed
    TRACE(format, 2, 3);
}
</code>```

Body:
I am trying to make compile time checks over the format of the printf. Here is the code.

#include <type_traits>
#include <iostream>

template <typename CHAR, typename ...ARGS>
constexpr size_t trace_cond(CHAR fmt, ARGS&&... args) {
   //always needs to pass
   return 1;
}

template <size_t N, typename ...ARGS>
constexpr size_t trace_cond(const char (&fmt)[N], ARGS&&... args) {
   //return parse(fmt) == args;
   return sizeof...(args) != 0;
}

#define TRACE(fmt, ...) { \
   static_assert(trace_cond(fmt, __VA_ARGS__), "Wrong ARGS"); \
   printf(fmt, ##__VA_ARGS__); \
}

int main(int argc, char* argv[]) {
  //working fine
  TRACE("%d %d\n", 2, 3);

  const char* format = "%d %d\n";
  //error
  TRACE(format, 2, 3);
}

So when the format is known at compile time I want to have a check(using static_assert) and if it is not known then the check should be not called or always to pass

Obs:

Currently the code is not compiling because const char *format is not declared constexpr

The main should not be change because TRACE macro is used in a large codebase but changes to TRACE are more than welcome

So my question is:
Is there a way to skip static_assert or make it pass when fmt type is const char *

Body:
I think you can do what you want by moving the static_assert to the trace_cond

#include <type_traits>
#include <iostream>

template <size_t C, typename CHAR>
size_t trace_cond(CHAR fmt) {
    //always needs to pass
    return 1;
}

template <typename ...ARGS>
constexpr size_t count_args(ARGS&&... args) {
    return sizeof...(args);
}

template <size_t C, size_t N>
constexpr size_t trace_cond(const char (&fmt)[N]) {
    // TODO, parse fmt and do the needed checks
    static_assert(C == 3, "");
    return 1;
}

#define TRACE(fmt, ...) { \
    trace_cond<count_args(__VA_ARGS__)>(fmt); \
    printf(fmt, ##__VA_ARGS__); \
}

int main(int argc, char* argv[]) {
    // Static check - hard coded to check for 3 arguments
    TRACE("%d %d %d\n", 2, 3, 4);

    const char* format = "%d %d\n";
    // No checks performed
    TRACE(format, 2, 3);
}


问:
Accessing state of another component in ReactJS?
I have 2 components, one of them has a state, which I want to access from the other component. </p>

```<code>class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {test:"Hello World"};
  }
  render() {
    return(<Bar {...this.state} />);
  }
}

class Bar extends React.Component {
  render() {
    return(<h1>{this.props.test}</h1>);
  }
}

ReactDOM.Render(
  <Bar />,
  document.getElementById("root")
);
</code>```

<p>I googled around a bit, but since I'm new to JS and React I think I misunderstood something, because this code doesn't work. From my understanding it should display "Hello World", but instead nothing happens. </p>

答:
You actually have three things going on. First as others have said, you should be using <Foo /> in your render method, and secondly, render should be lower case, (ReactDOM.render) not ReactDOM.Render.

Finally, trying to load the script.js file with babel they way you are, generates the following error for me in my developer console:

babel.min.js:24 Failed to load file:///C:script.js: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

The following works. Just put it in one file and open.

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link href="stylesheet.css" type="text/css" rel="stylesheet">
  <script src="https://unpkg.com/react@0.14.3/dist/react.js"></script>
  <script src="https://unpkg.com/react-dom@0.14.3/dist/react-dom.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    class Foo extends React.Component {
      constructor(props) {
        super(props);
        this.state = {test:"Hello World"};
      }
      render() {
        return(<Bar {...this.state} />);
      }
    }

    class Bar extends React.Component {
      render() {
        return(<h1>{this.props.test}</h1>);
      }
    }

    ReactDOM.render(
      <Foo />,
      document.getElementById("root")
    );
  </script>
</body>
</html>
</code>```

Body:
I have 2 components, one of them has a state, which I want to access from the other component.

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {test:"Hello World"};
  }
  render() {
    return(<Bar {...this.state} />);
  }
}

class Bar extends React.Component {
  render() {
    return(
{this.props.test}
);
  }
}

ReactDOM.Render(
  <Bar />,
  document.getElementById("root")
);

I googled around a bit, but since I'm new to JS and React I think I misunderstood something, because this code doesn't work. From my understanding it should display "Hello World", but instead nothing happens.

Body:
You actually have three things going on. First as others have said, you should be using <Foo /> in your render method, and secondly, render should be lower case, (ReactDOM.render) not ReactDOM.Render.

Finally, trying to load the script.js file with babel they way you are, generates the following error for me in my developer console:

babel.min.js:24 Failed to load file:///C:script.js: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

The following works. Just put it in one file and open.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link href="stylesheet.css" type="text/css" rel="stylesheet">
  <script src="https://unpkg.com/react@0.14.3/dist/react.js"></script>
  <script src="https://unpkg.com/react-dom@0.14.3/dist/react-dom.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    class Foo extends React.Component {
      constructor(props) {
        super(props);
        this.state = {test:"Hello World"};
      }
      render() {
        return(<Bar {...this.state} />);
      }
    }

    class Bar extends React.Component {
      render() {
        return(<h1>{this.props.test}</h1>);
      }
    }

    ReactDOM.render(
      <Foo />,
      document.getElementById("root")
    );
  </script>
</body>
</html>


问:
JAX-RS jersey ExceptionMapper: How to know the method who threw the exception
Im using JAX-RS jersey ExceptionMapper, and I'm wondering if there is a way to know inside the method toResponse(), which method (from the API) threw the exception.

Example (dummy code)

```<code>@javax.ws.rs.Path(“/bookstore/books/{bookID}”)
public class Book {
    @javax.ws.rs.GET
    public String informationMethod(String user) {
        ...
            throw new Exception("Error");
        ....
    }
}

@Provider
public class SomeMapper implements ExceptionMapper<Exception> {
    @Override
    public Response toResponse(Exception ex) {

        //a way to get the method name that threw the exception.
        //In the above example is: informationMethod.
        String methodName = //informationMethod

        return Response.status(500).entity(ex.getMessage()).type("text/plain")
                .build();
    }
}
</code>```

答:
Inject in to your ExceptionMapper mapper:

```<code>@Context private ResourceInfo resourceInfo;
</code>```

as it was suggested and do the following to get a method name:

```<code>resourceInfo.getResourceMethod()
</code>```

Body:
Im using JAX-RS jersey ExceptionMapper, and I'm wondering if there is a way to know inside the method toResponse(), which method (from the API) threw the exception.

Example (dummy code)

@javax.ws.rs.Path(“/bookstore/books/{bookID}”)
public class Book {
    @javax.ws.rs.GET
    public String informationMethod(String user) {
        ...
            throw new Exception("Error");
        ....
    }
}

@Provider
public class SomeMapper implements ExceptionMapper<Exception> {
    @Override
    public Response toResponse(Exception ex) {

        //a way to get the method name that threw the exception.
        //In the above example is: informationMethod.
        String methodName = //informationMethod

        return Response.status(500).entity(ex.getMessage()).type("text/plain")
                .build();
    }
}

Body:
Inject in to your ExceptionMapper mapper:

@Context private ResourceInfo resourceInfo;

as it was suggested and do the following to get a method name:

resourceInfo.getResourceMethod()


问:
Building triangle with nested loops
I'm trying to build a triangle using nested loops.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);```

I expected that each row is more than the last by only one "#" like this:

But this is the result I got:

答:
EDIT: Fixed it by just adding one line - you need to reinitialize the variable "line" after each row iteration

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  line="";
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);```

Title: Building triangle with nested loops

Body:
I'm trying to build a triangle using nested loops.

var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    line += "#";
  }
  triangle += line + "\n";
}

console.log(triangle);

I expected that each row is more than the last by only one "#" like this:

But this is the result I got: