问:
How to use tkinter and matplotlib to select points from a plot without closing it
I am trying to get some experience making an app using Tkinter. This practice app will display some data in a two panel plot, have a button to make new data and have the ability to select and highlight regions of the data. It is on that last part I am getting stuck. I have a class (PointSelector) that takes as inputs a list of the two axes (axarr), an integer to select which will be highlighted (ax2select), the figure (fig), the canvas (canv), # of ranges to highlight (NumRanges) and the data (xdat and ydat).

Unless I use the command plt.show() after the mpl_connect line, the code does not wait for the click event. But if I do use plt.show(), a new plot window comes up (which I don't want) and matplotlib will block until ALL windows are closed (I want the window to stay open after thigh highlighting is complete).

Is there a way to release matplotlib from blocking once the mpl_disconnect is called (and also not have the second window appear i.e. using plt.plot()) ? Or is there a way to use the event system of matplotlib without using the command plt.show()?

```<code>import Tkinter as tk
import numpy as np
import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import tkFileDialog

LARGE_FONT = ("Verdana", 12)

class PointSelector():
'''
classdocs
'''
def __init__(self, axarr, ax2select, fig, canv, NumRanges, xdat, ydat):
    '''
    Constructor
    '''
    self.axarr = axarr
    self.ax2select = ax2select
    self.fig = fig
    self.canv = canv
    self.NumRanges = NumRanges
    SelectedPoints = []
    self.Ranges = []
    self.xdat = xdat
    self.ydat = ydat
    self.Nselected = 0
    self.SelectedL = False
    self.SelectedR = False
    self.LeftArr = []
    self.RightArr = []
    self.cid = canv.mpl_connect('button_press_event', self.onclick)
#         plt.ion()
#         plt.show()
    canv.show()

    print 'Done With ALL!'

    def PlotRange(self,rng):
        x = self.xdat[range(rng[0],rng[1]+1)]
        y = self.ydat[range(rng[0],rng[1]+1)]
        self.axarr[self.ax2select].plot(x,y,color='r')

        self.canv.draw()

    def PlotPoint(self,x,y):
        self.axarr[self.ax2select].scatter(x,y,color='r')
        self.canv.draw()

    def onclick(self, event):
        print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
      (event.button, event.x, event.y, event.xdata, event.ydata))

        if event.inaxes == self.axarr[self.ax2select]:

            xval = np.argmin(np.abs(event.xdata-self.xdat))
            if self.SelectedL:
                self.RightArr.append(xval)
                self.SelectedR = True
                self.PlotPoint(self.xdat[xval], self.ydat[xval])
            else:
                self.LeftArr.append(xval)
                self.SelectedL = True
                self.PlotPoint(self.xdat[xval], self.ydat[xval])

            if self.SelectedL and self.SelectedR:
                self.SelectedL = False
                self.SelectedR = False
                self.Nselected += 1
                self.PlotRange([self.LeftArr[-1], self.RightArr[-1]])
                if self.Nselected == self.NumRanges:
                    for i in range(len(self.LeftArr)):
                        self.Ranges.append([self.LeftArr[i], self.RightArr[i]])
                    self.canv.mpl_disconnect(self.cid)
                    print 'Done With Selection'

        else:
            print 'Outside Window'

class Driver(tk.Tk):
'''
classdocs
'''
    def __init__(self, *args, **kwargs):
    '''
    Constructor
    '''
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both",expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = dict()
        F = StartPage
        frame = F(container, self)
        self.frames[F] = frame
        frame.grid(row=0,column=0,sticky="nsew")
        self.show_frame(StartPage)
    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):
'''
classdocs
'''

    def __init__(self, parent, controller):
    '''
    Constructor
    '''
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self,text="Start Page", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        quitButton = tk.Button(self, text="Quit",command=self._quit)
        quitButton.pack(side="bottom")

        NewDataButton = tk.Button(self, text="Get New Data",command=self.GetNewData)
        NewDataButton.pack(side="top")

        menu = tk.Menu(parent)
        controller.config(menu=menu)

        submenuFile = tk.Menu(menu)
        menu.add_cascade(label="File",menu=submenuFile)
        submenuFile.add_command(label='Open File', command=self.onOpen)
        submenuFile.add_command(label='Load Configuration File', command=self.onOpen)
        submenuFile.add_separator()

        submenuFile.add_command(label='Exit', command=self._quit)

        submenuContinuum = tk.Menu(menu)
        menu.add_cascade(label="Continuum",menu=submenuContinuum)

        canvas_width = 100
        canvas_height = 100
        canv = tk.Canvas(self,width=canvas_width,height=canvas_height)
        canv.pack()

        self.x = np.linspace(0.0,4.0*np.pi,100)

        self.fig = plt.figure(figsize=(6,6))

        self.axarr = []
        self.axarr.append(plt.subplot(211))
        self.axarr.append(plt.subplot(212))

        self.canv = FigureCanvasTkAgg(self.fig,master=self)
        self.canv.show()
        self.canv.get_tk_widget().pack()
        self.canv._tkcanvas.pack(side=tk.TOP,fill=tk.BOTH,expand=1)
        self.GetNewData()

        self.txt=tk.Text(self)
        submenuContinuum.add_command(label='Select Continuum',
                                 command=lambda:PointSelector(self.axarr, 0, self.fig, self.canv, 2,
                                                            self.x, self.y))
        submenuContinuum.add_command(label='Remove Continuum', command=donothing)

    def GetNewData(self):
        rnum = (np.random.rand(1))
        print rnum
        self.y = np.sin(self.x)*(np.random.rand(1)*4.0)*(self.x)**rnum
        self.dy = np.gradient(self.y, self.x[1]-self.x[0])
        self.DrawData()
    def DrawData(self):
        self.axarr[0].clear()
        self.axarr[1].clear()
        self.axarr[0].plot(self.x,self.y)
        self.axarr[1].plot(self.x,self.dy)

        self.canv.draw()

    def onOpen(self):

        ftypes = [('Python files', '*.py'), ('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes = ftypes)
        fl = dlg.show()

        if fl != '':
            text = self.readFile(fl)
            self.txt.insert('end', text)

    def readFile(self, filename):

        f = open(filename, "r")
        text = f.read()
        return text

    def _quit(self):
        self.controller.quit()
        self.controller.destroy()

def donothing():
    print "nothing"

if __name__ == '__main__':
    app = Driver()
    app.mainloop()
</code>```

答:
First, it is correct that you don't want to use plt.show() or plt.ion() in your GUI, because they would interfere with the GUI window.

You would probably also want to get rid of canv.show() in the PointSelector's initialization method (simply because I don't know what it should do there and the __init__ is not the method in the program that needs to redraws things.).

So assuming the point selector is otherwise fine, the actual problem comes from the line

```<code>.add_command(label='...', command=lambda:PointSelector(...))
</code>```

where it is instantiated in an anonymous function. The problem with this is that you have now no way of using this instance in your program and that it will be lost, once its __init__ is finished.

Together with this comes the problem that you loose the reference to the matplotlib callback.

The matplotlib event handling tutorial states:

The canvas retains only weak references to the callbacks. Therefore if a callback is a method of a class instance, you need to retain a reference to that instance. Otherwise the instance will be garbage-collected and the callback will vanish.

So in order to be able to use the PointSelector in your programm you would need to assign it to a class variable, e.g. self.selector = PointSelector(..). This can be done inside a method which is called as command from the Menu.

A possible solution would then look like:

```<code>class StartPage(tk.Frame):

    #...

    def __init__(self, parent, controller):
        submenuContinuum.add_command(label='Select Continuum',
                                 command=self.registerSelector)
        submenuContinuum.add_command(label='Remove Continuum', command=donothing)

    def registerSelector(self):
        self.selector = PointSelector(self.axarr, 0, self.fig,
                                      self.canv, 2, self.x, self.y)
</code>```

Body:
I am trying to get some experience making an app using Tkinter. This practice app will display some data in a two panel plot, have a button to make new data and have the ability to select and highlight regions of the data. It is on that last part I am getting stuck. I have a class (PointSelector) that takes as inputs a list of the two axes (axarr), an integer to select which will be highlighted (ax2select), the figure (fig), the canvas (canv), # of ranges to highlight (NumRanges) and the data (xdat and ydat).

Unless I use the command plt.show() after the mpl_connect line, the code does not wait for the click event. But if I do use plt.show(), a new plot window comes up (which I don't want) and matplotlib will block until ALL windows are closed (I want the window to stay open after thigh highlighting is complete).

Is there a way to release matplotlib from blocking once the mpl_disconnect is called (and also not have the second window appear i.e. using plt.plot()) ? Or is there a way to use the event system of matplotlib without using the command plt.show()?

import Tkinter as tk
import numpy as np
import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import tkFileDialog

LARGE_FONT = ("Verdana", 12)

class PointSelector():
'''
classdocs
'''
def __init__(self, axarr, ax2select, fig, canv, NumRanges, xdat, ydat):
    '''
    Constructor
    '''
    self.axarr = axarr
    self.ax2select = ax2select
    self.fig = fig
    self.canv = canv
    self.NumRanges = NumRanges
    SelectedPoints = []
    self.Ranges = []
    self.xdat = xdat
    self.ydat = ydat
    self.Nselected = 0
    self.SelectedL = False
    self.SelectedR = False
    self.LeftArr = []
    self.RightArr = []
    self.cid = canv.mpl_connect('button_press_event', self.onclick)
#         plt.ion()
#         plt.show()
    canv.show()

    print 'Done With ALL!'

    def PlotRange(self,rng):
        x = self.xdat[range(rng[0],rng[1]+1)]
        y = self.ydat[range(rng[0],rng[1]+1)]
        self.axarr[self.ax2select].plot(x,y,color='r')

        self.canv.draw()

    def PlotPoint(self,x,y):
        self.axarr[self.ax2select].scatter(x,y,color='r')
        self.canv.draw()

    def onclick(self, event):
        print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
      (event.button, event.x, event.y, event.xdata, event.ydata))

        if event.inaxes == self.axarr[self.ax2select]:

            xval = np.argmin(np.abs(event.xdata-self.xdat))
            if self.SelectedL:
                self.RightArr.append(xval)
                self.SelectedR = True
                self.PlotPoint(self.xdat[xval], self.ydat[xval])
            else:
                self.LeftArr.append(xval)
                self.SelectedL = True
                self.PlotPoint(self.xdat[xval], self.ydat[xval])

            if self.SelectedL and self.SelectedR:
                self.SelectedL = False
                self.SelectedR = False
                self.Nselected += 1
                self.PlotRange([self.LeftArr[-1], self.RightArr[-1]])
                if self.Nselected == self.NumRanges:
                    for i in range(len(self.LeftArr)):
                        self.Ranges.append([self.LeftArr[i], self.RightArr[i]])
                    self.canv.mpl_disconnect(self.cid)
                    print 'Done With Selection'

        else:
            print 'Outside Window'

class Driver(tk.Tk):
'''
classdocs
'''
    def __init__(self, *args, **kwargs):
    '''
    Constructor
    '''
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both",expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = dict()
        F = StartPage
        frame = F(container, self)
        self.frames[F] = frame
        frame.grid(row=0,column=0,sticky="nsew")
        self.show_frame(StartPage)
    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):
'''
classdocs
'''

    def __init__(self, parent, controller):
    '''
    Constructor
    '''
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self,text="Start Page", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        quitButton = tk.Button(self, text="Quit",command=self._quit)
        quitButton.pack(side="bottom")

        NewDataButton = tk.Button(self, text="Get New Data",command=self.GetNewData)
        NewDataButton.pack(side="top")

        menu = tk.Menu(parent)
        controller.config(menu=menu)

        submenuFile = tk.Menu(menu)
        menu.add_cascade(label="File",menu=submenuFile)
        submenuFile.add_command(label='Open File', command=self.onOpen)
        submenuFile.add_command(label='Load Configuration File', command=self.onOpen)
        submenuFile.add_separator()

        submenuFile.add_command(label='Exit', command=self._quit)

        submenuContinuum = tk.Menu(menu)
        menu.add_cascade(label="Continuum",menu=submenuContinuum)

        canvas_width = 100
        canvas_height = 100
        canv = tk.Canvas(self,width=canvas_width,height=canvas_height)
        canv.pack()

        self.x = np.linspace(0.0,4.0*np.pi,100)

        self.fig = plt.figure(figsize=(6,6))

        self.axarr = []
        self.axarr.append(plt.subplot(211))
        self.axarr.append(plt.subplot(212))

        self.canv = FigureCanvasTkAgg(self.fig,master=self)
        self.canv.show()
        self.canv.get_tk_widget().pack()
        self.canv._tkcanvas.pack(side=tk.TOP,fill=tk.BOTH,expand=1)
        self.GetNewData()

        self.txt=tk.Text(self)
        submenuContinuum.add_command(label='Select Continuum',
                                 command=lambda:PointSelector(self.axarr, 0, self.fig, self.canv, 2,
                                                            self.x, self.y))
        submenuContinuum.add_command(label='Remove Continuum', command=donothing)

    def GetNewData(self):
        rnum = (np.random.rand(1))
        print rnum
        self.y = np.sin(self.x)*(np.random.rand(1)*4.0)*(self.x)**rnum
        self.dy = np.gradient(self.y, self.x[1]-self.x[0])
        self.DrawData()
    def DrawData(self):
        self.axarr[0].clear()
        self.axarr[1].clear()
        self.axarr[0].plot(self.x,self.y)
        self.axarr[1].plot(self.x,self.dy)

        self.canv.draw()

    def onOpen(self):

        ftypes = [('Python files', '*.py'), ('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes = ftypes)
        fl = dlg.show()

        if fl != '':
            text = self.readFile(fl)
            self.txt.insert('end', text)

    def readFile(self, filename):

        f = open(filename, "r")
        text = f.read()
        return text

    def _quit(self):
        self.controller.quit()
        self.controller.destroy()

def donothing():
    print "nothing"

if __name__ == '__main__':
    app = Driver()
    app.mainloop()

Body:
First, it is correct that you don't want to use plt.show() or plt.ion() in your GUI, because they would interfere with the GUI window.

You would probably also want to get rid of canv.show() in the PointSelector's initialization method (simply because I don't know what it should do there and the __init__ is not the method in the program that needs to redraws things.).

So assuming the point selector is otherwise fine, the actual problem comes from the line

.add_command(label='...', command=lambda:PointSelector(...))

where it is instantiated in an anonymous function. The problem with this is that you have now no way of using this instance in your program and that it will be lost, once its __init__ is finished.

Together with this comes the problem that you loose the reference to the matplotlib callback.

The matplotlib event handling tutorial states:

The canvas retains only weak references to the callbacks. Therefore if a callback is a method of a class instance, you need to retain a reference to that instance. Otherwise the instance will be garbage-collected and the callback will vanish.

So in order to be able to use the PointSelector in your programm you would need to assign it to a class variable, e.g. self.selector = PointSelector(..). This can be done inside a method which is called as command from the Menu.

A possible solution would then look like:

class StartPage(tk.Frame):

    #...

    def __init__(self, parent, controller):
        submenuContinuum.add_command(label='Select Continuum',
                                 command=self.registerSelector)
        submenuContinuum.add_command(label='Remove Continuum', command=donothing)

    def registerSelector(self):
        self.selector = PointSelector(self.axarr, 0, self.fig,
                                      self.canv, 2, self.x, self.y)


来源: stackexchange

问:
How to perform pagination with the Litho framework?
I am implementing a Retrofit APi for getting data from the server and showing this in a RecyclerView using the Litho framework, and it's doing well. As all of us know when we have infinite data to show in recyclerview we have to implement the pagination pattern. And I know this, but I am confused how to implement this in the Litho framework. Litho the provides onScrollListener() method:

final Component component = Recycler.create(context)
    .binder(recyclerBinder)
    .onScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            //
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //
        })
    .build();
```

I don't know: how to use a customized EndlessRecyclerViewScrollListener for endless scrolling in Litho?

答:
I have had success implementing the "infinite" scroll pattern leveraging the recyclerBinder within the onScrolled method of a OnScrollListener. A trivial example would be the following:

```<code>//Initialize the RecyclerBinder
recyclerBinder = new RecyclerBinder(c, new LinearLayoutInfo(getContext(), OrientationHelper.VERTICAL, false));

//Initialize a recycler component
Component component = Recycler.create(c)
                .onScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);

                        // use the recyclerBinder to determine what items at what position are visible -
                        // (you could also use the findLastVisibleItemPosition() method depending on your implementation)
                        int firstVisibleItemPosition = recyclerBinder.findFirstVisibleItemPosition();

                        //check if it is within range relative to the current available items and is not loading (room to improve/modify logic pending use case)
                        if((recyclerBinder.getItemCount() - 5) <= firstVisibleItemPosition && !isLoading) {
                            //if so - use your service to get the next page
                            service.getNextPage();
                        }
                    }
                })
                .build();
</code>```

Then in a call back method - you can insert your items starting at the item count

```<code>public void callback(List<T> results) {
    int position = recyclerBinder.getItemCount();
    for(T result: results) {
        Component component = //assemble your component(s) ...
        ComponentInfo.Builder info = ComponentInfo.create().component(component);
        recyclerBinder.insertItemAt(position, info.build());
        position++;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am implementing a Retrofit APi for getting data from the server and showing this in a RecyclerView using the Litho framework, and it's doing well. As all of us know when we have infinite data to show in recyclerview we have to implement the pagination pattern. And I know this, but I am confused how to implement this in the Litho framework. Litho the provides onScrollListener() method:

final Component component = Recycler.create(context)
    .binder(recyclerBinder)
    .onScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            //
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //
        })
    .build();

I don't know: how to use a customized EndlessRecyclerViewScrollListener for endless scrolling in Litho?

Body:
I have had success implementing the "infinite" scroll pattern leveraging the recyclerBinder within the onScrolled method of a OnScrollListener. A trivial example would be the following:

//Initialize the RecyclerBinder
recyclerBinder = new RecyclerBinder(c, new LinearLayoutInfo(getContext(), OrientationHelper.VERTICAL, false));

//Initialize a recycler component
Component component = Recycler.create(c)
                .onScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);

                        // use the recyclerBinder to determine what items at what position are visible -
                        // (you could also use the findLastVisibleItemPosition() method depending on your implementation)
                        int firstVisibleItemPosition = recyclerBinder.findFirstVisibleItemPosition();

                        //check if it is within range relative to the current available items and is not loading (room to improve/modify logic pending use case)
                        if((recyclerBinder.getItemCount() - 5) <= firstVisibleItemPosition && !isLoading) {
                            //if so - use your service to get the next page
                            service.getNextPage();
                        }
                    }
                })
                .build();

Then in a call back method - you can insert your items starting at the item count

public void callback(List<T> results) {
    int position = recyclerBinder.getItemCount();
    for(T result: results) {
        Component component = //assemble your component(s) ...
        ComponentInfo.Builder info = ComponentInfo.create().component(component);
        recyclerBinder.insertItemAt(position, info.build());
        position++;
    }
}


问:
Why beaglebone black uboot is configured to CONFIG_SYS_CPU="armv7". When bbb is armv8?
Looking into .config file after configuring uboot for bbb using

make am335x_boneblack_defconfig

It shows:-

```<code>CONFIG_SYS_ARCH="arm"
CONFIG_SYS_CPU="armv7"
CONFIG_SYS_SOC="am33xx"
CONFIG_SYS_VENDOR="ti"
CONFIG_SYS_BOARD="am335x"
CONFIG_SYS_CONFIG_NAME="am335x_evm"
</code>```

Why uboot for bbb is configured to armv7 as it is armv8 ?

I am trying to explore bootloaders. I am trying to write a new bootloader.
So a/c to above configuration, bootloader for armv7 should work fine for armv8 ?

I am confused , as it is armv8 which supports both aarch32 and aarch64 execution states.
If it is in AArch64 , then it has different instruction set.

In what mode the processor configuration just before loading  uboot ?

Please let me know if this is not the correct forum to ask.

答: The Beaglebone Black ships with an SoC that is based on the ARM Cortex-A8, which is an ARMv7 CPU core.</p>

Body:
Looking into .config file after configuring uboot for bbb using

make am335x_boneblack_defconfig

It shows:-

CONFIG_SYS_ARCH="arm"
CONFIG_SYS_CPU="armv7"
CONFIG_SYS_SOC="am33xx"
CONFIG_SYS_VENDOR="ti"
CONFIG_SYS_BOARD="am335x"
CONFIG_SYS_CONFIG_NAME="am335x_evm"

Why uboot for bbb is configured to armv7 as it is armv8 ?

I am trying to explore bootloaders. I am trying to write a new bootloader.
So a/c to above configuration, bootloader for armv7 should work fine for armv8 ?

I am confused , as it is armv8 which supports both aarch32 and aarch64 execution states.
If it is in AArch64 , then it has different instruction set.

In what mode the processor configuration just before loading  uboot ?

Please let me know if this is not the correct forum to ask.


问:
EventSource is not working in Angular 4
I am new to Angular 4 and I am trying to create an EventSource to subscribe and receive events. I started with the following code:

```<code>import { Injectable} from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class MyService implements OnInit {

  constructor(private http: Http) {
    const eventSource = new EventSource('/events');
    eventSource.onmessage = x => console.log(JSON.parse(x.data));
  }
}
</code>```

I got the following error:

```<code>[ts] Cannot find name 'EventSource'.
</code>```

Then, I added the following import:

```<code>import { EventSource } from 'eventsource';
</code>```

An error appeared in the browser's console:

```<code>Uncaught (in promise): TypeError:
__WEBPACK_IMPORTED_MODULE_2_eventsource_lib_eventsource_js__.EventSource is not a constructor
</code>```

I also tried to add

```<code>"eventsource": "1.0.2"
</code>```

to my package.json, re-install using npm install, launch the project using npm start, but the issue persisted.

答:
I assume, that problem is that this library exports a function. And you expect the object. Try to import everything and give it a name:
import * as EventSource from 'eventsource';
Than you can use it as a constructor.

Title: EventSource is not working in Angular 4

Body:
I am new to Angular 4 and I am trying to create an EventSource to subscribe and receive events. I started with the following code:

import { Injectable} from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class MyService implements OnInit {

  constructor(private http: Http) {
    const eventSource = new EventSource('/events');
    eventSource.onmessage = x => console.log(JSON.parse(x.data));
  }
}

I got the following error:

[ts] Cannot find name 'EventSource'.

Then, I added the following import:

import { EventSource } from 'eventsource';

An error appeared in the browser's console:

Uncaught (in promise): TypeError:
__WEBPACK_IMPORTED_MODULE_2_eventsource_lib_eventsource_js__.EventSource is not a constructor

I also tried to add

"eventsource": "1.0.2"

to my package.json, re-install using npm install, launch the project using npm start, but the issue persisted.


问:
VB.NET - Split Number into multiple ones
I was workin on a small tool lately for checking and editing MS SQL Databases. But now I'm standing in front of a wall. I want to split a big number from a column to several small ones. For example I have the number 195872323 and I want it to be shown as 195 Diamonds 872 Gold 323 Platinum idk. How can I split this number into this kinda String?

Thanks to everbody for helpin me.

答:
To create the string you want, use this. I should add that Stack Overflow isn't strictly a code writing service, but it was quick and easy.. You original number is originally the essentially number of platinum -  assuming 1000 platinum per gold and 1000 gold per diamond

```<code>Private Function SplitToCurrency(x As Integer) As String
    Dim diamonds As Integer = CInt(Math.Truncate(CDec(x / 1000000)))
    Dim gold As Integer = CInt(Math.Truncate(CDec(x - diamonds * 1000000) / 1000))
    Dim platinum As Integer = x - diamonds * 1000000 - gold * 1000
    Return diamonds.ToString & " Diamonds " & gold.ToString & " Gold " & platinum.ToString & " Platinum"
End Function
</code>```

Diamonds are calculated by dividing the original number by 1,000,000 and removing the decimal

and so on for the rest.

Body:
To create the string you want, use this. I should add that Stack Overflow isn't strictly a code writing service, but it was quick and easy.. You original number is originally the essentially number of platinum -  assuming 1000 platinum per gold and 1000 gold per diamond

Private Function SplitToCurrency(x As Integer) As String
    Dim diamonds As Integer = CInt(Math.Truncate(CDec(x / 1000000)))
    Dim gold As Integer = CInt(Math.Truncate(CDec(x - diamonds * 1000000) / 1000))
    Dim platinum As Integer = x - diamonds * 1000000 - gold * 1000
    Return diamonds.ToString & " Diamonds " & gold.ToString & " Gold " & platinum.ToString & " Platinum"
End Function

Diamonds are calculated by dividing the original number by 1,000,000 and removing the decimal

and so on for the rest.


问:
How to update Azure PowerShell?
I have Azure PowerShell 1.0.3 installed via the Gallery (per the instructions here in the Installing Azure PowerShell From The Gallery section). I want to update to the latest version but am unclear on the commands that I need to run. I tried the following, but decided to ask rather than potentially corrupt my installation:

```<code>PS C:\Windows\system32> Install-Module AzureRM

You are installing the module(s) from an untrusted repository. If you trust this repository, change its
InstallationPolicy value by running the Set-PSRepository cmdlet.
Are you sure you want to install software from 'https://www.powershellgallery.com/api/v2/'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): y
WARNING: Version '1.0.3' of module 'AzureRM' is already installed at 'C:\Program
Files\WindowsPowerShell\Modules\AzureRM\1.0.3'. To delete version '1.0.3' and install version '1.1.0', run
Install-Module, and add the -Force parameter.
</code>```

Can someone provide a script to update Azure PowerShell?

答: It appears the command has changed a bit, I had to use Install-Module -Force AzureRM -AllowClobber to get it to update

Title: How to update Azure PowerShell?

Body:
I have Azure PowerShell 1.0.3 installed via the Gallery (per the instructions here in the Installing Azure PowerShell From The Gallery section). I want to update to the latest version but am unclear on the commands that I need to run. I tried the following, but decided to ask rather than potentially corrupt my installation:

PS C:\Windows\system32> Install-Module AzureRM

You are installing the module(s) from an untrusted repository. If you trust this repository, change its
InstallationPolicy value by running the Set-PSRepository cmdlet.
Are you sure you want to install software from 'https://www.powershellgallery.com/api/v2/'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): y
WARNING: Version '1.0.3' of module 'AzureRM' is already installed at 'C:\Program
Files\WindowsPowerShell\Modules\AzureRM\1.0.3'. To delete version '1.0.3' and install version '1.1.0', run
Install-Module, and add the -Force parameter.

Can someone provide a script to update Azure PowerShell?


问:
read Json data in android studio
I am building an app in android studio that uses JSON to acess to my postgresql where is my data and I am receiving the data this way:

```<code>[
{"id":"1","title":"12 May to 30 Jun"},
{"id":"2","title":"3 Jun to 20 Jun"}
]
</code>```

I tried to find every where how to use JSONObject or JSONArray for "unlock" the data for pass it to other variables

答:
Here is the working code:

```<code>public void parseJson() {

    // Response from API call
    String response = "[{\"id\":\"1\",\"title\":\"12 May to 30 Jun\"},\n" +
                       "{\"id\":\"2\",\"title\":\"3 Jun to 20 Jun\"}]";

    try {
        JSONArray jsonArray = new JSONArray(response);

        // Get all jsonObject from jsonArray
        for (int i = 0; i < jsonArray.length(); i++)
        {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            String id = null, title = null;

            // Id
            if (jsonObject.has("id") && !jsonObject.isNull("id")) {
                id = jsonObject.getString("id");
            }

            // Title
            if (jsonObject.has("title") && !jsonObject.isNull("title")) {
                title = jsonObject.getString("title");
            }

            Log.d("SUCCESS", "JSON Object: " + "\nId: " + id
                                             + "\nTitle: " + title);
        }
    } catch (JSONException e) {
        Log.e("FAILED", "Json parsing error: " + e.getMessage());
    }
}
</code>```

OUTPUT:

```<code>D/SUCCESS: JSON Object:
           Id: 1
           Title: 12 May to 30 Jun

D/SUCCESS: JSON Object:
           Id: 2
           Title: 3 Jun to 20 Jun
</code>```

Title: read Json data in android studio

Body:
I am building an app in android studio that uses JSON to acess to my postgresql where is my data and I am receiving the data this way:

[
{"id":"1","title":"12 May to 30 Jun"},
{"id":"2","title":"3 Jun to 20 Jun"}
]

I tried to find every where how to use JSONObject or JSONArray for "unlock" the data for pass it to other variables

Body:
Here is the working code:

public void parseJson() {

    // Response from API call
    String response = "[{\"id\":\"1\",\"title\":\"12 May to 30 Jun\"},\n" +
                       "{\"id\":\"2\",\"title\":\"3 Jun to 20 Jun\"}]";

    try {
        JSONArray jsonArray = new JSONArray(response);

        // Get all jsonObject from jsonArray
        for (int i = 0; i < jsonArray.length(); i++)
        {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            String id = null, title = null;

            // Id
            if (jsonObject.has("id") && !jsonObject.isNull("id")) {
                id = jsonObject.getString("id");
            }

            // Title
            if (jsonObject.has("title") && !jsonObject.isNull("title")) {
                title = jsonObject.getString("title");
            }

            Log.d("SUCCESS", "JSON Object: " + "\nId: " + id
                                             + "\nTitle: " + title);
        }
    } catch (JSONException e) {
        Log.e("FAILED", "Json parsing error: " + e.getMessage());
    }
}

OUTPUT:

D/SUCCESS: JSON Object:
           Id: 1
           Title: 12 May to 30 Jun

D/SUCCESS: JSON Object:
           Id: 2
           Title: 3 Jun to 20 Jun


问:
What the best delegate or get superview?
Can anyone help me to give reason to use delegate/protocol oriented or get superview, as I know swift use protocol oriented on code but for grab parent view or controller we still can use get superview like

Get superview example:

```<code>extension UIView {

  var parentViewController: UIViewController? {
    var parentResponder: UIResponder? = self
    while parentResponder != nil {
        parentResponder = parentResponder!.next
        if let viewController = parentResponder as? UIViewController {
            return viewController
        }
    }
    return nil
  }
}
</code>```

Use delegate example:

```<code>protocol SomeDelegate {
  func didClick()
}

class Child {
  var delegate: SomeDelegate?
}
</code>```

What Pros and Cons to use delegate or get superview ?

Example for parentView:

```<code>class Cell {

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    self.parentViewController.view.makeToast("Something !")
  }
}
</code>```

Example for delegate:

```<code>class Parent: SomeDelegate {
  func didClick() {
    self.view.makeToast("Something !")
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? Cell
    cell.delegate = self

    return cell
  }
}

class Cell {
  var label: UILabel
  var delegate: SomeDelegate?

  func configure() {
    label.addGestureRecognizer(UILongPressGestureRecognizer(
        target: self,
        action: #selector(copyAction(_:))
    ))
  }

  @objc private func copyAction(_ sender: UILongPressGestureRecognizer) {
    guard let delegate = self.delegate else {
      return
    }

    delegate.didClick()
  }
}
</code>```

答:
Delegate is preferred, not the superview. some reasons below

A view added in stack is not always retained in memory after its addition. especially when no strong reference maintained (this differs when view added from XIB or SB). So in this case calling superview might sometime crash with an unrecognized selector sent on some random instance.

One can create a view and never add to another view. ex for sake of removing you might comment just addsubview line leaving other code as is. At this time also the superview is nil.

Usage of custom views under uicontrols with own reusable view stack like Collectionview,TableView etc. would change superviews in runtime. so not always guaranteed to call same superview instance.

Body:
Can anyone help me to give reason to use delegate/protocol oriented or get superview, as I know swift use protocol oriented on code but for grab parent view or controller we still can use get superview like

Get superview example:

extension UIView {

  var parentViewController: UIViewController? {
    var parentResponder: UIResponder? = self
    while parentResponder != nil {
        parentResponder = parentResponder!.next
        if let viewController = parentResponder as? UIViewController {
            return viewController
        }
    }
    return nil
  }
}

Use delegate example:

protocol SomeDelegate {
  func didClick()
}

class Child {
  var delegate: SomeDelegate?
}

What Pros and Cons to use delegate or get superview ?

Example for parentView:

class Cell {

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    self.parentViewController.view.makeToast("Something !")
  }
}

Example for delegate:

class Parent: SomeDelegate {
  func didClick() {
    self.view.makeToast("Something !")
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? Cell
    cell.delegate = self

    return cell
  }
}

class Cell {
  var label: UILabel
  var delegate: SomeDelegate?

  func configure() {
    label.addGestureRecognizer(UILongPressGestureRecognizer(
        target: self,
        action: #selector(copyAction(_:))
    ))
  }

  @objc private func copyAction(_ sender: UILongPressGestureRecognizer) {
    guard let delegate = self.delegate else {
      return
    }

    delegate.didClick()
  }
}


问:
In Complexity Analysis why is ++ considered to be 2 operations?
In my Computer Science II class, the professor considers ++,--,*=, etc. to be 2 operations. However, at the Assembly level this is not really two operations. Can someone explain or is this just for the sake of simplicity?</p>

答:
It should be more than 2 in my opinion since it has two meanings depending on context and I always have to remind myself of them when I see it.

a = b++ is the same as a = b; b = b + 1

and

a = ++b is the same as b = b + 1; a = b

This is enough of a confusion to send most first year students off the cliff.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Allain Lalonde


问:
swig/python: object does not support indexing
Given this set of files:

foo.h:

```<code>#pragma once

#include <stdio.h>

template <class T0> class Foo {
  public:
    T0 m[3];

    Foo(const T0 &a, const T0 &b, const T0 &c) {
        m[0] = a;
        m[1] = b;
        m[2] = c;
    }
    void info() { printf("%d %d %d\n", m[0], m[1], m[2]); }
    // T0 &operator[](int id) { return ((T0 *)m)[id]; }
};
</code>```

foo.cpp:

```<code>#include "foo.h"
</code>```

foo.i (Attempt1):

```<code>%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%template(intFoo) Foo<int>;

%extend Foo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}
</code>```

setup.py:

```<code>import os
import sys
from setuptools import setup, Extension

foo_module = Extension('_foo',
                           sources=[
                               'foo.i',
                               'foo.cpp'
                           ],
                           swig_opts=['-c++', '-py3', '-builtin'],
                           include_dirs=['.']
                           )

setup(name='foo',
      version='0.1',
      platforms=['Windows', 'Linux'],
      ext_modules=[foo_module],
      py_modules=["foo"],
      )
</code>```

test.py:

```<code>from foo import intFoo

a = intFoo(10,20,30)
print(dir(a))
a.info()
print(a[2])
</code>```

I build the extension running:

```<code>python setup.py build_ext --force -i
</code>```

but when i try to run test.py i'll get:

```<code>TypeError: 'foo.intFoo' object does not support indexing
</code>```

The statement extend in foo.i is the answer suggested on any other SO related threads, that means I'm using it incorrectly here. Could anyone explain how to fix this so when i run test.py is able to use the [] operator succesfully?

Another attempts:

Attempt2:

```<code>%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%template(intFoo) Foo<int>;

%extend intFoo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}
</code>```

Throws this error TypeError: 'foo.intFoo' object does not support indexing

Attempt3

```<code>%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%extend Foo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}

%template(intFoo) Foo<int>;
</code>```

Throws this error foo_wrap.cpp(3808): error C2065: 'm': undeclared identifier

答:
I have changed the wrong answer (stating that %extent could only be used without the -builtin option) to something that works, but again only without the 'built-in' option

setup.py

```<code>import os
import sys
from setuptools import setup, Extension

foo_module = Extension('_foo',
                           sources=[
                               'foo.i', 'foo.cpp'
                           ],
                           swig_opts=['-c++'],
                           include_dirs=['.']
                           )

setup(name='foo',
      version='0.1',
      platforms=['Windows', 'Linux'],
      ext_modules=[foo_module],
      py_modules=["foo"],
      )
</code>```

foo.i

```<code>%module foo

%{
#include "foo.h"
%}

%include "carrays.i"
%array_functions(int, intArray);

%include "foo.h"

%extend Foo<int> {
%pythoncode %{
def __getitem__(self, id):
  return _foo.intArray_getitem(self.m,id)
%}
};

%template(intFoo) Foo<int>;
</code>```

Note, how the extension is generating Python code, which allows you to do many sophisticated things.

Old answer:

According to the SWIG documentation the python layer is stripped off and thereby the %extend feature is ignored (this is incorrect, the proxy objects are not created)

See http://www.swig.org/Doc3.0/SWIGDocumentation.html

36.4.2 Built-in Types

When -builtin is used, the pure python layer is stripped off. Each
  wrapped class is turned into a new python built-in type which inherits
  from SwigPyObject, and SwigPyObject instances are returned directly
  from the wrapped methods. For more information about python built-in
  extensions, please refer to the python documentation:

Body:
Given this set of files:

foo.h:

#pragma once

#include <stdio.h>

template <class T0> class Foo {
  public:
    T0 m[3];

    Foo(const T0 &a, const T0 &b, const T0 &c) {
        m[0] = a;
        m[1] = b;
        m[2] = c;
    }
    void info() { printf("%d %d %d\n", m[0], m[1], m[2]); }
    // T0 &operator[](int id) { return ((T0 *)m)[id]; }
};

foo.cpp:

#include "foo.h"

foo.i (Attempt1):

%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%template(intFoo) Foo<int>;

%extend Foo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}

setup.py:

import os
import sys
from setuptools import setup, Extension

foo_module = Extension('_foo',
                           sources=[
                               'foo.i',
                               'foo.cpp'
                           ],
                           swig_opts=['-c++', '-py3', '-builtin'],
                           include_dirs=['.']
                           )

setup(name='foo',
      version='0.1',
      platforms=['Windows', 'Linux'],
      ext_modules=[foo_module],
      py_modules=["foo"],
      )

test.py:

from foo import intFoo

a = intFoo(10,20,30)
print(dir(a))
a.info()
print(a[2])

I build the extension running:

python setup.py build_ext --force -i

but when i try to run test.py i'll get:

TypeError: 'foo.intFoo' object does not support indexing

The statement extend in foo.i is the answer suggested on any other SO related threads, that means I'm using it incorrectly here. Could anyone explain how to fix this so when i run test.py is able to use the [] operator succesfully?

Another attempts:

Attempt2:

%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%template(intFoo) Foo<int>;

%extend intFoo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}

Throws this error TypeError: 'foo.intFoo' object does not support indexing

Attempt3

%module foo

%{
#include "foo.h"
%}

%include "foo.h"

%extend Foo{
    T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}

%template(intFoo) Foo<int>;

Throws this error foo_wrap.cpp(3808): error C2065: 'm': undeclared identifier

Body:
I have changed the wrong answer (stating that %extent could only be used without the -builtin option) to something that works, but again only without the 'built-in' option

setup.py

import os
import sys
from setuptools import setup, Extension

foo_module = Extension('_foo',
                           sources=[
                               'foo.i', 'foo.cpp'
                           ],
                           swig_opts=['-c++'],
                           include_dirs=['.']
                           )

setup(name='foo',
      version='0.1',
      platforms=['Windows', 'Linux'],
      ext_modules=[foo_module],
      py_modules=["foo"],
      )

foo.i

%module foo

%{
#include "foo.h"
%}

%include "carrays.i"
%array_functions(int, intArray);

%include "foo.h"

%extend Foo<int> {
%pythoncode %{
def __getitem__(self, id):
  return _foo.intArray_getitem(self.m,id)
%}
};

%template(intFoo) Foo<int>;

Note, how the extension is generating Python code, which allows you to do many sophisticated things.

Old answer:

According to the SWIG documentation the python layer is stripped off and thereby the %extend feature is ignored (this is incorrect, the proxy objects are not created)

See http://www.swig.org/Doc3.0/SWIGDocumentation.html

36.4.2 Built-in Types

When -builtin is used, the pure python layer is stripped off. Each
  wrapped class is turned into a new python built-in type which inherits
  from SwigPyObject, and SwigPyObject instances are returned directly
  from the wrapped methods. For more information about python built-in
  extensions, please refer to the python documentation:


问:
How to use PixiJS in web worker
I need to display a quite complex 2D shape in a canvas using PixiJS and to do so I'd like to create and define all graphic elements in a separate thread (web worker) to not block the rest of the UI.

The problem is that when I import PixiJS in the web worker file like this

```<code>importScripts('https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.5.2/pixi.js');
</code>```

it gives me an error because it accesses DOM elements (like window and document) and this is not allowed in web workers. How can I solve this?

This is the error:

```<code>Uncaught ReferenceError: window is not defined
at Object.179../Math.sign (Object.assign.js:3)
at s (_prelude.js:1)
at _prelude.js:1
at Object.<anonymous> (WebGLPrepare.js:101)
at Object.187../accessibility (index.js:44)
at s (_prelude.js:1)
at e (_prelude.js:1)
at _prelude.js:1
at _prelude.js:1
at _prelude.js:1
</code>```

答:
Well I guess you cannot. Webworkers have their own DedicatedWorkerGlobalScope with no access to the DOM, window, etc. If you have heavy computations, for instance to calculate animations, all you can do is let the webworker do the number crunching and the main thread do the rendering.

The Worker and the main thread cannot share objects. Even if the following explanation is not 100% technically correct, you can imagine that if you:

```<code>var obj = { a: { b: 100 } };
worker.postMessage(obj);
</code>```

It will be more like:

```<code>                   //really dirty object clone here
worker.postMessage(JSON.parse(JSON.stringify(obj)));
</code>```

With that I want to point out, that you cannot share objects with the worker and vice verca.

Find a tecnically correct explaintion here:

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Transferring_data_to_and_from_workers_further_details

Title: How to use PixiJS in web worker

Body:
I need to display a quite complex 2D shape in a canvas using PixiJS and to do so I'd like to create and define all graphic elements in a separate thread (web worker) to not block the rest of the UI.

The problem is that when I import PixiJS in the web worker file like this

importScripts('https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.5.2/pixi.js');

it gives me an error because it accesses DOM elements (like window and document) and this is not allowed in web workers. How can I solve this?

This is the error:

Uncaught ReferenceError: window is not defined
at Object.179../Math.sign (Object.assign.js:3)
at s (_prelude.js:1)
at _prelude.js:1
at Object.<anonymous> (WebGLPrepare.js:101)
at Object.187../accessibility (index.js:44)
at s (_prelude.js:1)
at e (_prelude.js:1)
at _prelude.js:1
at _prelude.js:1
at _prelude.js:1

Body:
Well I guess you cannot. Webworkers have their own DedicatedWorkerGlobalScope with no access to the DOM, window, etc. If you have heavy computations, for instance to calculate animations, all you can do is let the webworker do the number crunching and the main thread do the rendering.

The Worker and the main thread cannot share objects. Even if the following explanation is not 100% technically correct, you can imagine that if you:

var obj = { a: { b: 100 } };
worker.postMessage(obj);

It will be more like:

                   //really dirty object clone here
worker.postMessage(JSON.parse(JSON.stringify(obj)));

With that I want to point out, that you cannot share objects with the worker and vice verca.

Find a tecnically correct explaintion here:

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Transferring_data_to_and_from_workers_further_details


问:
CSS and modifying div's width if radio button checked
JavaScript not accepted this time.

So, I have this CSS code. This code should change to width if radio button is checked. Nothing happens. How could I modify the code?

```<code>input[type="radio"]#someID-1:checked #extra { width: 4000px; }
</code>```

I also have this HTML code:

```<code><div id="kaaviotaulukko" style="white-space: nowrap; position: relative; text-align: center;">
  <div style="display: inline-block">
    <div style="DISPLAY:INLINE-BLOCK">
      <input id="someID-1" name="nappi" type="radio">
      <div class="listaus-sisalto" style="float:left;width:0">
        <div id="navi3">
          <div style="z-index:100;position:fixed;right:0;top:300px">
            <span><label for="someID-1">1</label></span>
          </div>
        </div>
      </div>
      <div class="kierros" style="display: inline-block;width:350px">
        R1
      </div>
    </div>
    <div style="DISPLAY:INLINE-BLOCK">
      <input id="someID-5" name="nappi" type="radio">
      <div class="listaus-sisalto" style="float:right;width:0">
        <div id="navi5"></div>
      </div>
      <div class="kierros" id="extra" style="display: inline-block;width:70px">
        extra
      </div>
    </div>
    <input id="someID-100" name="nappi" type="radio">
    <div class="listaus-sisalto" style="float:right;width:0">
      <div id="navi100"></div>
    </div>
    <div style="z-index:99;width:70px;position:fixed;left:0;top:100px;margin:auto;background-color:red">
      <br>
    </div>
    <div style="z-index:99;width:70px;position:fixed;right:0;top:100px;margin:auto;background-color:red">
      <br>
    </div>
  </div>
</div>
</code>```

答:
A simplified version of what you'd like to become.

#radiodiv {
    background: red;
}

#radio:checked + #radiodiv {
    width: 400px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="radio" type="radio" />

<div id="radiodiv">
<p>This is the div</p>
</div></code>```

Body:
JavaScript not accepted this time.

So, I have this CSS code. This code should change to width if radio button is checked. Nothing happens. How could I modify the code?

input[type="radio"]#someID-1:checked #extra { width: 4000px; }

I also have this HTML code:

      <input id="someID-1" name="nappi" type="radio">

            1

        R1

      <input id="someID-5" name="nappi" type="radio">

        extra

    <input id="someID-100" name="nappi" type="radio">

Body:
A simplified version of what you'd like to become.

#radiodiv {
    background: red;
}

#radio:checked + #radiodiv {
    width: 400px;
}

<input id="radio" type="radio" />

<div id="radiodiv">
<p>This is the div</p>
</div>


问:
Visual Command Prompt commands not available
I have VS17 installed and have been studying C# for a while. Ever since I began, I was asked to run the ildasm.exe application, but that didn't work since in my Visual Stidio Command Prompt, when I type ildasm or ildasm.exe, it just says that the command doesn't exist.

I was able to curb that by adding the ildasm.exe application directly to the "Tools" menu of VS17 and accessing it from there and I also copied the path to the "Environment path" so that I could access it through PowerShell directly.

But now I'm being asked to access another application called dumpbin.exe, which has the same problem I initially had with ildasm.exe in the Visual Command Prompt, but this one I simply can't find the path in order to access it and I've googled and searched this website in search of the path, but I only found it for older versions of VS,  which were of no use and running a search through my machine I wasn't able to find it either.

Can anyone help me find what is wrong with my Visual Command Prompt that makes these commands not available?l

答:
With proper installation of VS you should have no problem with running Developer Command Prompt for VS 2017 and access all the commands from there.

So maybe you should check it if there are no issues there.

With DUMPBIN there might be a different case. It is part of C/C++ Build tools so you might not have them installed. Open the VS installer and check if you have this part on your machine.

And the path that this tool is installed is:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\dumpbin.exe


问:
Angular 2 ES5 filter with TS
I cannot make ES5 filter function works with Angular 2 (with TypeScript).

My filter function looks like this:

```<code>getApplicableNotes(): void {
this.noteService
  .getNotes()
  .then(notes => {
    notes.filter((note) => !note._deleted && !note._done);
    this.notes = notes;
  })
  .catch((error) => this.error = error);
}
</code>```

My TypeScript class is extremely straightforward:

```<code>export class Note {
  id: number;
  title: string;
  description: string;
  _starred = false;
  _done = false;
  _deleted = false;

  constructor(id: number, title: string, description: string, starred?: boolean, done?: boolean, deleted?: boolean) {
    this.id = id;
    this.title = title;
    this.description = description;
    this._starred = starred ? starred : false;
    this._done = done ? done : false;
    this._deleted = deleted ? deleted : false;
  };

}
</code>```

Although, my notes array is never filtered, no matter what properties I will set up in Note constructor.

答:
The filter() method doesn't modify the array, but returns a new filtered array. You should assign the result to this.notes:

```<code>.then(notes => {
  this.notes = notes.filter((note) => !note._deleted && !note._done);
})
</code>```

ContentLicense: CC BY-SA 4.0

Title: Angular 2 ES5 filter with TS

Body:
I cannot make ES5 filter function works with Angular 2 (with TypeScript).

My filter function looks like this:

getApplicableNotes(): void {
this.noteService
  .getNotes()
  .then(notes => {
    notes.filter((note) => !note._deleted && !note._done);
    this.notes = notes;
  })
  .catch((error) => this.error = error);
}

My TypeScript class is extremely straightforward:

export class Note {
  id: number;
  title: string;
  description: string;
  _starred = false;
  _done = false;
  _deleted = false;

  constructor(id: number, title: string, description: string, starred?: boolean, done?: boolean, deleted?: boolean) {
    this.id = id;
    this.title = title;
    this.description = description;
    this._starred = starred ? starred : false;
    this._done = done ? done : false;
    this._deleted = deleted ? deleted : false;
  };

}

Although, my notes array is never filtered, no matter what properties I will set up in Note constructor.

Body:
The filter() method doesn't modify the array, but returns a new filtered array. You should assign the result to this.notes:

.then(notes => {
  this.notes = notes.filter((note) => !note._deleted && !note._done);
})


问:
If Let vs Guard Let for UIImage in Swift 1.2
I am working my way through the iOS Apple Developer Tutorial, but am having a bit of an issue since my computer's version of Swift is 1.2 and Xcode is 6.4 instead of Swift 3.0.  I've been able to work along-side downgrading the code as need, but have hit an error in "guard let", which was introduced in Swift 2.0, below:

```<code>// The info dictionary may contain multiple representations of the image.
// You want to use the original.

guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
    fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
</code>```

I converted it to the following:

```<code>if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
     return selectedImage
} else {
     fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}

//Set photoImageView to display the image.
photoImageView.image = selectedImage
</code>```

but I got the following error: "Use of unresolved identified 'selectedImage'"

Any help would be greatly appreciated!

EDIT: FULL CODE BELOW

```<code>import UIKit

class ViewController: UIViewController, UITextFieldDelegate,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {

//MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var mealNameLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    //Handle the text field's user input through the delegate callbacks
    nameTextField.delegate = self
}

//MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
    //Hide the keyboard
    textField.resignFirstResponder()
    return true
}
func textFieldDidEndEditing(textField: UITextField) {
    //Set the lablel name as what the used typed
    mealNameLabel.text = textField.text
}

//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    //Dismiss the picker if the user canceled
    dismissViewControllerAnimated(true, completion:nil)
}
func imagePickerController(picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [String : Any]) {
        //The info dictionary may contain multiple representations of the image. You want to use the original.
        if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            //Set photoImageView to display the image
            photoImageView.image = selectedImage
        } else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }

        //Set photoImageView to display the image
        //photoImageView.image = selectedImage

        //Dismiss the picker
        dismissViewControllerAnimated(true, completion: nil)
}

//MARK: Actions
@IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
    //Hide the keyboard
    nameTextField.resignFirstResponder()

    //UIImagePickerController is a view controller that lets a user pick media from their photo library.
    let imagePickerController = UIImagePickerController()

    //Only allow photos to be picked, not taken.
    imagePickerController.sourceType = .PhotoLibrary

    //Make sure ViewController is notified when the user picks and image.
    imagePickerController.delegate = self
    presentViewController(imagePickerController, animated: true, completion: nil)

}
@IBAction func setDefaultLabelText(_: UIButton) {
    mealNameLabel.text = "Default Text"
}
}
</code>```

答:
this happens because you have the variable selectedImage is defined only inside your if let scope

You must use this code instead

```<code>if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
     //Set photoImageView to display the image.
     photoImageView.image = selectedImage
     return selectedImage
} else {
     fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
</code>```

I hope this helps

Body:
I am working my way through the iOS Apple Developer Tutorial, but am having a bit of an issue since my computer's version of Swift is 1.2 and Xcode is 6.4 instead of Swift 3.0.  I've been able to work along-side downgrading the code as need, but have hit an error in "guard let", which was introduced in Swift 2.0, below:

// The info dictionary may contain multiple representations of the image.
// You want to use the original.

guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
    fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}

I converted it to the following:

if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
     return selectedImage
} else {
     fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}

//Set photoImageView to display the image.
photoImageView.image = selectedImage

but I got the following error: "Use of unresolved identified 'selectedImage'"

Any help would be greatly appreciated!

EDIT: FULL CODE BELOW

import UIKit

class ViewController: UIViewController, UITextFieldDelegate,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {

//MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var mealNameLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    //Handle the text field's user input through the delegate callbacks
    nameTextField.delegate = self
}

//MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
    //Hide the keyboard
    textField.resignFirstResponder()
    return true
}
func textFieldDidEndEditing(textField: UITextField) {
    //Set the lablel name as what the used typed
    mealNameLabel.text = textField.text
}

//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    //Dismiss the picker if the user canceled
    dismissViewControllerAnimated(true, completion:nil)
}
func imagePickerController(picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [String : Any]) {
        //The info dictionary may contain multiple representations of the image. You want to use the original.
        if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            //Set photoImageView to display the image
            photoImageView.image = selectedImage
        } else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }

        //Set photoImageView to display the image
        //photoImageView.image = selectedImage

        //Dismiss the picker
        dismissViewControllerAnimated(true, completion: nil)
}

//MARK: Actions
@IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
    //Hide the keyboard
    nameTextField.resignFirstResponder()

    //UIImagePickerController is a view controller that lets a user pick media from their photo library.
    let imagePickerController = UIImagePickerController()

    //Only allow photos to be picked, not taken.
    imagePickerController.sourceType = .PhotoLibrary

    //Make sure ViewController is notified when the user picks and image.
    imagePickerController.delegate = self
    presentViewController(imagePickerController, animated: true, completion: nil)

}
@IBAction func setDefaultLabelText(_: UIButton) {
    mealNameLabel.text = "Default Text"
}
}

Body:
this happens because you have the variable selectedImage is defined only inside your if let scope

You must use this code instead

if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
     //Set photoImageView to display the image.
     photoImageView.image = selectedImage
     return selectedImage
} else {
     fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}

I hope this helps


问:
What are the most common scenarios where one should prefer BigDecimal or Double in Java?

Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10-scale).

That is what the doc says. Based on the docs it appears that BigDecimal i useful when

You are dealing with super large numbers

You are concerned about precision

But are there any other scenarios where BigDecimal is a better choice ?

答:
Double is a floating value, meaning that it is not an exact value. Therefore, you need to use BigDecimal which gives you the exact value.
Double will display only 15 significant decimal digits but you can have as many significant digits in BigDecimal as you wish. You can set the value using MathContext class.
BigDecimal is used when you are writing code for developing applications like scientific calculators.</p>


问:
C# How to change MenuItem's text in the OnClick
I am trying to change the text of a MenuItem inside a ContextMenu. I thought I have done this before, but I cannot remember.

Here is what I have:

```<code>private void TrayIcon_Click(object sender, EventArgs e)
        {
            MessageBox.Show(((MenuItem)sender).Text);
            if(((MenuItem)sender).Text.Equals("Pause"))
            {
                icon.ContextMenu.MenuItems[0].Text = "Unpause";
                shouldPause = true;
            }

            if(((MenuItem)sender).Text.Equals("Unpause"))
            {
                icon.ContextMenu.MenuItems[0].Text = "Pause";
                shouldPause = false;
            }

            if(((MenuItem)sender).Text.Equals("Exit"))
            {
                icon.Visible = false;
                Application.Exit();
            }
        }
</code>```

When I try to change "Pause" to "Unpause" it doesn't work. However, if I try to change "Pause" to "Pizza", it actually works.. What the heck..

Thanks all!

EDIT:

Changed my code to the following:

```<code>private void TrayIcon_Click(object sender, EventArgs e)
        {
            if(((MenuItem)sender).Text.Equals("Pause"))
            {
                shouldPause = true;
            }

            if(((MenuItem)sender).Text.Equals("Unpause"))
            {
                shouldPause = false;
            }

            if(((MenuItem)sender).Text.Equals("Exit"))
            {
                icon.Visible = false;
                Application.Exit();
            }
            string text = "Pause";

            if(shouldPause)
            {
                text = "Unpause";
            }
            icon.ContextMenu.MenuItems[0].Text = text;
        }
</code>```

And now it works.

Was it because I was trying to change the text on the item too soon after being clicked?

答:
Based on your observation, I am assuming that icon.ContextMenu.MenuItems[0] and (MenuItem)sender are the same menu item.

That would explain why it didn’t work with your first code:

```<code>if(((MenuItem)sender).Text.Equals("Pause"))
{
    icon.ContextMenu.MenuItems[0].Text = "Unpause";
    shouldPause = true;
}

if(((MenuItem)sender).Text.Equals("Unpause"))
{
    icon.ContextMenu.MenuItems[0].Text = "Pause";
    shouldPause = false;
}
</code>```

The problem becomes a bit more clear when you introduce local variables:

```<code>var senderItem = (MenuItem)sender;
var firstItem = icon.ContextMenu.MenuItems[0];

if(senderItem.Text.Equals("Pause"))
{
    firstItem.Text = "Unpause";
    shouldPause = true;
}

if(senderItem.Text.Equals("Unpause"))
{
    firstItem.Text = "Pause";
    shouldPause = false;
}
</code>```

If now senderItem and firstItem are the same, then what this code does is the following:

Check if the text is Pause

Change the text to Unpause

Set shouldPause to true

Check if the text is Unpause

Change the text to Pause

Set shouldPause to false

So basically, since these are separate ifs, they both run, with the second overwriting the first.

You can generally avoid this by using else if instead of multiple separate/unliked if:

```<code>if(senderItem.Text.Equals("Pause"))
{
    firstItem.Text = "Unpause";
    shouldPause = true;
}
else if(senderItem.Text.Equals("Unpause"))
{
    firstItem.Text = "Pause";
    shouldPause = false;
}
</code>```

Now, only one of those branches will ever run.

Body:
I am trying to change the text of a MenuItem inside a ContextMenu. I thought I have done this before, but I cannot remember.

Here is what I have:

private void TrayIcon_Click(object sender, EventArgs e)
        {
            MessageBox.Show(((MenuItem)sender).Text);
            if(((MenuItem)sender).Text.Equals("Pause"))
            {
                icon.ContextMenu.MenuItems[0].Text = "Unpause";
                shouldPause = true;
            }

            if(((MenuItem)sender).Text.Equals("Unpause"))
            {
                icon.ContextMenu.MenuItems[0].Text = "Pause";
                shouldPause = false;
            }

            if(((MenuItem)sender).Text.Equals("Exit"))
            {
                icon.Visible = false;
                Application.Exit();
            }
        }

When I try to change "Pause" to "Unpause" it doesn't work. However, if I try to change "Pause" to "Pizza", it actually works.. What the heck..

Thanks all!

EDIT:

Changed my code to the following:

private void TrayIcon_Click(object sender, EventArgs e)
        {
            if(((MenuItem)sender).Text.Equals("Pause"))
            {
                shouldPause = true;
            }

            if(((MenuItem)sender).Text.Equals("Unpause"))
            {
                shouldPause = false;
            }

            if(((MenuItem)sender).Text.Equals("Exit"))
            {
                icon.Visible = false;
                Application.Exit();
            }
            string text = "Pause";

            if(shouldPause)
            {
                text = "Unpause";
            }
            icon.ContextMenu.MenuItems[0].Text = text;
        }

And now it works.

Was it because I was trying to change the text on the item too soon after being clicked?

Body:
Based on your observation, I am assuming that icon.ContextMenu.MenuItems[0] and (MenuItem)sender are the same menu item.

That would explain why it didn’t work with your first code:

if(((MenuItem)sender).Text.Equals("Pause"))
{
    icon.ContextMenu.MenuItems[0].Text = "Unpause";
    shouldPause = true;
}

if(((MenuItem)sender).Text.Equals("Unpause"))
{
    icon.ContextMenu.MenuItems[0].Text = "Pause";
    shouldPause = false;
}

The problem becomes a bit more clear when you introduce local variables:

var senderItem = (MenuItem)sender;
var firstItem = icon.ContextMenu.MenuItems[0];

if(senderItem.Text.Equals("Pause"))
{
    firstItem.Text = "Unpause";
    shouldPause = true;
}

if(senderItem.Text.Equals("Unpause"))
{
    firstItem.Text = "Pause";
    shouldPause = false;
}

If now senderItem and firstItem are the same, then what this code does is the following:

Check if the text is Pause

Change the text to Unpause

Set shouldPause to true

Check if the text is Unpause

Change the text to Pause

Set shouldPause to false

So basically, since these are separate ifs, they both run, with the second overwriting the first.

You can generally avoid this by using else if instead of multiple separate/unliked if:

if(senderItem.Text.Equals("Pause"))
{
    firstItem.Text = "Unpause";
    shouldPause = true;
}
else if(senderItem.Text.Equals("Unpause"))
{
    firstItem.Text = "Pause";
    shouldPause = false;
}

Now, only one of those branches will ever run.


问:
Creating lists based on two conditions
I am trying to create lists based on data from users.  The data is a 16 question survey, and so I want to split the data into a list of the 16 answers, or a list that is just answers = ['No data available]  My code so far is shown below.

```<code>studentanswers = []
contains_data = False
temp = []
for i in answers:
if i == 'No data available':
    if contains_data:
        studentanswers.append(temp)
        temp = []
        studentanswers.append([i])
        contains_data = False
    else:
        studentanswers.append([i])
else:
    contains_data = True
    if len(temp) < 16:
        temp.append(i)
    else:
        studentanswers.append(temp)
        temp = []
        contains_data = False
</code>```

However, as I iterate, the data gets off the correct count, and some of the data gets assigned to the wrong user.  For example, question 16 for student 1 will become question 1 for student 2.

答:
Try something along these lines:</p>

```<code>while answers:
    if answers[0] = 'No data available':
        studentanswers.append(['No data available'])
        answers = answers[1:]
    else:
       studentanswers.append(answers[:16])
       answers = answers[16:]
</code>```

Title: Creating lists based on two conditions

Body:
I am trying to create lists based on data from users.  The data is a 16 question survey, and so I want to split the data into a list of the 16 answers, or a list that is just answers = ['No data available]  My code so far is shown below.

studentanswers = []
contains_data = False
temp = []
for i in answers:
if i == 'No data available':
    if contains_data:
        studentanswers.append(temp)
        temp = []
        studentanswers.append([i])
        contains_data = False
    else:
        studentanswers.append([i])
else:
    contains_data = True
    if len(temp) < 16:
        temp.append(i)
    else:
        studentanswers.append(temp)
        temp = []
        contains_data = False

However, as I iterate, the data gets off the correct count, and some of the data gets assigned to the wrong user.  For example, question 16 for student 1 will become question 1 for student 2.

Body:
Try something along these lines:

while answers:
    if answers[0] = 'No data available':
        studentanswers.append(['No data available'])
        answers = answers[1:]
    else:
       studentanswers.append(answers[:16])
       answers = answers[16:]


问:
Why is using decorator factory factory functions a syntax error?
Say I have a decorator factory factory. It is quite useless, just accumulating the arguments, and adding to the results, but just for an example:

```<code>def decorator_factory_factory(a):
    def decorator_factory(b):
        def decorator(f):
            def decorated(*args, **kwargs):
                return f(*args, **kwargs) + a + b
            return decorated
        return decorator
    return decorator_factory
</code>```

And I try to use it like this:

```<code>@decorator_factory_factory(3)(1)
def should_return_5():
    return 1
</code>```

I get a SyntaxError. Surely it should allow any arbitrary Python expression as a decorator?

I also tried:

```<code>@(decorator_factory_factory(3)(1))
def should_not_be_touched():
    return 1
</code>```

but this was another SyntaxError.

Am I doing something wrong? The only way I have found around this is:

```<code>_decorator_factory = decorator_factory_factory(3)
@_decorator_factory(1)
def should_not_be_touched():
    return 1
del _decorator_factory
</code>```

But this requires an additional variable that needs to be deleted

答:
the function was send on wrong wrapper and never called </p>

```<code>def decorator_factory_factory():
    def decorator_factory(f):
        def decorator():
            return f()
        return decorator
    return decorator_factory

@decorator_factory_factory()
def should_not_be_touched():
    return 1
</code>```

Body:
Say I have a decorator factory factory. It is quite useless, just accumulating the arguments, and adding to the results, but just for an example:

def decorator_factory_factory(a):
    def decorator_factory(b):
        def decorator(f):
            def decorated(*args, **kwargs):
                return f(*args, **kwargs) + a + b
            return decorated
        return decorator
    return decorator_factory

And I try to use it like this:

@decorator_factory_factory(3)(1)
def should_return_5():
    return 1

I get a SyntaxError. Surely it should allow any arbitrary Python expression as a decorator?

I also tried:

@(decorator_factory_factory(3)(1))
def should_not_be_touched():
    return 1

but this was another SyntaxError.

Am I doing something wrong? The only way I have found around this is:

_decorator_factory = decorator_factory_factory(3)
@_decorator_factory(1)
def should_not_be_touched():
    return 1
del _decorator_factory

But this requires an additional variable that needs to be deleted

Body:
the function was send on wrong wrapper and never called

def decorator_factory_factory():
    def decorator_factory(f):
        def decorator():
            return f()
        return decorator
    return decorator_factory

@decorator_factory_factory()
def should_not_be_touched():
    return 1


问:
How to prevent Black Screen when switching activities?
I am working on a Project and testing the XML, however, whenever I try switching to my next activity, the app gets stuck on a black screen and does nothing, and I am forced to quit.

I tried switching the layouts for setContentView and that didn't work, I checked to make sure the code in the activity files was working, and now I am looking at other's questions and I am just confused.

Here is my MainActivity:

```<code>public class MainActivity extends android.app.Activity {

ImageButton startButton;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);

    startButton = (ImageButton)findViewById(R.id.startButton);
    textView = (TextView)findViewById(R.id.textView);
    textView.setTextColor(Color.WHITE);
    View backgroundView = findViewById(R.id.spoopySkellington);
    View root = backgroundView.getRootView();
    root.setBackgroundColor(getResources().getColor(android.R.color.black));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

public void startClick(View view)
{
    final Intent intent = new Intent(MainActivity.this, AdventureActivity.class);
    startActivity(intent);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
</code>```

Here is the activity I am trying to switch to.

```<code>public class AdventureActivity extends android.app.Activity {

Character mainCharacter;
Character skeleton;
TextView dialogueView;
EditText textField;
Button confirmButton;
String field;
ImageView enemy;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_adventure);

    confirmButton = (Button)findViewById(R.id.confirmButton);
    dialogueView = (TextView)findViewById(R.id.dialogueView);
    textField = (EditText)findViewById(R.id.inputText);
    field = "";

    skeleton = new Character("Skeleton", 10, 1);
    String name = "";
    while (field.equals("")) {
        dialogueView.setText("What is your name?");
        name = field;
    }

    mainCharacter = new Character(name);

}

public void onClick(View view)
{
    field = textField.getText().toString();
    textField.setText("");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
</code>```

Lastly, here is the activity xml for the one I want to switch to:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.jason.textadventure.AdventureActivity"
tools:showIn="@layout/activity_adventure">

<TextView
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:id="@+id/dialogueView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="..."
    android:textSize="30dp"
    tools:layout_editor_absoluteY="126dp"
    tools:layout_editor_absoluteX="180dp"
    />

<EditText
    app:layout_constraintBottom_toBottomOf="@id/dialogueView"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:id="@+id/inputText"
    android:layout_width="261dp"
    android:layout_height="40dp"
    tools:layout_editor_absoluteY="196dp"
    tools:layout_editor_absoluteX="62dp"
    android:inputType="textNoSuggestions"
    />

<Button
    app:layout_constraintBottom_toBottomOf="@id/inputText"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@id/dialogueView"
    android:id="@+id/confirmButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CONFIRM"
    android:onClick="onClick"
    tools:layout_editor_absoluteY="184dp"
    tools:layout_editor_absoluteX="148dp" />
</code>```

答:
When onCreate() is called, your code is stuck around this loop</p>

```<code>while (field.equals("")) {
        dialogueView.setText("What is your name?");
        name = field;
    }
</code>```

Body:
I am working on a Project and testing the XML, however, whenever I try switching to my next activity, the app gets stuck on a black screen and does nothing, and I am forced to quit.

I tried switching the layouts for setContentView and that didn't work, I checked to make sure the code in the activity files was working, and now I am looking at other's questions and I am just confused.

Here is my MainActivity:

public class MainActivity extends android.app.Activity {

ImageButton startButton;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);

    startButton = (ImageButton)findViewById(R.id.startButton);
    textView = (TextView)findViewById(R.id.textView);
    textView.setTextColor(Color.WHITE);
    View backgroundView = findViewById(R.id.spoopySkellington);
    View root = backgroundView.getRootView();
    root.setBackgroundColor(getResources().getColor(android.R.color.black));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

public void startClick(View view)
{
    final Intent intent = new Intent(MainActivity.this, AdventureActivity.class);
    startActivity(intent);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Here is the activity I am trying to switch to.

public class AdventureActivity extends android.app.Activity {

Character mainCharacter;
Character skeleton;
TextView dialogueView;
EditText textField;
Button confirmButton;
String field;
ImageView enemy;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_adventure);

    confirmButton = (Button)findViewById(R.id.confirmButton);
    dialogueView = (TextView)findViewById(R.id.dialogueView);
    textField = (EditText)findViewById(R.id.inputText);
    field = "";

    skeleton = new Character("Skeleton", 10, 1);
    String name = "";
    while (field.equals("")) {
        dialogueView.setText("What is your name?");
        name = field;
    }

    mainCharacter = new Character(name);

}

public void onClick(View view)
{
    field = textField.getText().toString();
    textField.setText("");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Lastly, here is the activity xml for the one I want to switch to:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.jason.textadventure.AdventureActivity"
tools:showIn="@layout/activity_adventure">

<TextView
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:id="@+id/dialogueView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="..."
    android:textSize="30dp"
    tools:layout_editor_absoluteY="126dp"
    tools:layout_editor_absoluteX="180dp"
    />

<EditText
    app:layout_constraintBottom_toBottomOf="@id/dialogueView"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:id="@+id/inputText"
    android:layout_width="261dp"
    android:layout_height="40dp"
    tools:layout_editor_absoluteY="196dp"
    tools:layout_editor_absoluteX="62dp"
    android:inputType="textNoSuggestions"
    />

<Button
    app:layout_constraintBottom_toBottomOf="@id/inputText"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@id/dialogueView"
    android:id="@+id/confirmButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CONFIRM"
    android:onClick="onClick"
    tools:layout_editor_absoluteY="184dp"
    tools:layout_editor_absoluteX="148dp" />

Body:
When onCreate() is called, your code is stuck around this loop

while (field.equals("")) {
        dialogueView.setText("What is your name?");
        name = field;
    }


答:
The question maybe has some good sizes to check, for example the financial one is an example, I'll took it from here because I liked it:

Primer on Financial Issues

Currency calculations require precision to a specific degree, such as two digits after the decimal for most currencies. They also require a specific type of rounding behavior, such as always rounding up in the case of taxes.

For example, suppose we have a product which costs 10.00 in a given currency and the local sales tax is 0.0825, or 8.25%. If we work it out on paper, the tax amount is,

10.00 * 0.0825 = 0.825

Because our precision for the currency is two digits after the decimal, we need to round the 0.825 figure. Also, because this is a tax, it is good practice to always round up to the next highest cent. That way when the accounts are balanced at the end of the day, we never find ourselves underpaying taxes.

0.825 -> 0.83

And so the total we charge to the customer is 10.83 in the local currency and pay 0.83 to the tax collector. Note that if we sold 1000 of these, we would have overpaid the collector by this much,

1000 * (0.83 - 0.825) = 5.00

Another important issue is where to do the rounding in a given computation. Suppose we sold Liquid Nitrogen at 0.528361 per liter. A customer comes in and buys 100.00 liters, so we write out the total price,

100.0 * 0.528361 = 52.8361

Because this isn't a tax, we can round this either up or down at our discretion. Suppose we round according to standard rounding rules: If the next significant digit is less than 5, then round down. Otherwise round up. This gives us a figure of 52.84 for the final price.

Now suppose we want to give a promotional discount of 5% off the entire purchase. Do we apply this discount on the 52.8361 figure or the 52.84 figure? What's the difference?

Calculation 1: 52.8361 * 0.95 = 50.194295 = 50.19  Calculation 2:
  52.84 * 0.95 = 50.198 = 50.20

Note that we rounded the final figure by using the standard rounding rule.

See how there's a difference of one cent between the two figures? The old code never bothered to consider rounding, so it always did computations as in Calculation 1. But in the new code we always round before applying promotions, taxes, and so on, just like in Calculation 2. This is one of the main reasons for the one cent error.

Title: What are the most common scenarios where one should prefer BigDecimal or Double in Java?

Body:
Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10-scale).

That is what the doc says. Based on the docs it appears that BigDecimal i useful when

You are dealing with super large numbers

You are concerned about precision

But are there any other scenarios where BigDecimal is a better choice ?


问:
How to use a future without waiting for it?
The following example is taken from a C++ async tutorial:

```<code>#include <future>
#include <iostream>
#include <vector>

int twice(int m) { return 2 * m; }

int main() {
  std::vector<std::future<int>> futures;
  for(int i = 0; i < 10; ++i) { futures.push_back (std::async(twice, i)); }

  //retrive and print the value stored in the future
  for(auto &e : futures) { std::cout << e.get() << std::endl; }
  return 0;
}
</code>```

How can I use the result of a future without waiting for it? Ie I would like to do something like this:

```<code>  int sum = 0;
  for(auto &e : futures) { sum += someLengthyCalculation(e.get()); }
</code>```

I could pass a reference to the future to someLengthyCalculation, but at some point I have to call get to retrieve the value, thus I dont know how to write it without waiting for the first element being completed, before the next one can start summing.

答:
The design of futures lends itself to this kind of solution, where you create more futures representing the calculated values:</p>

```<code>  std::vector<std::future<int>> calculated_futures;

  for (auto &e : futures) {
      calculated_futures.push_back(
          std::async([&e]{ return someLengthyCalculation(e.get()); })
      );
  }

  int sum = 0;
  for(auto &e : calculated_futures) { sum += e.get(); }
</code>```

Body:
The following example is taken from a C++ async tutorial:

#include <future>
#include <iostream>
#include <vector>

int twice(int m) { return 2 * m; }

int main() {
  std::vector<std::future<int>> futures;
  for(int i = 0; i < 10; ++i) { futures.push_back (std::async(twice, i)); }

  //retrive and print the value stored in the future
  for(auto &e : futures) { std::cout << e.get() << std::endl; }
  return 0;
}

How can I use the result of a future without waiting for it? Ie I would like to do something like this:

  int sum = 0;
  for(auto &e : futures) { sum += someLengthyCalculation(e.get()); }

I could pass a reference to the future to someLengthyCalculation, but at some point I have to call get to retrieve the value, thus I dont know how to write it without waiting for the first element being completed, before the next one can start summing.

Body:
The design of futures lends itself to this kind of solution, where you create more futures representing the calculated values:

  std::vector<std::future<int>> calculated_futures;

  for (auto &e : futures) {
      calculated_futures.push_back(
          std::async([&e]{ return someLengthyCalculation(e.get()); })
      );
  }

  int sum = 0;
  for(auto &e : calculated_futures) { sum += e.get(); }


问:
mysql fulltext search and special chars
I'm using php + mysql with a full text index.
I have the following contents in the field I want to search:

"Hello: it's a test!"

"Hello i am also a test!"

When I search for "hello:", it finds both rows.
But It should only find the first row - at least until I search for "hello%".
The colon seems not tot be treated as a "normal" charakter.

答:
This might be far to late but I can't reproduce your problem.

I have a table with your two entries:

```<code>Table: Test
ID Note
-- ---------
1  Hello: it's a test!
2  Hello i am also a test!
</code>```

If I run your first search SELECT * FROM test t WHERE Note LIKE "Hello:" I get 0 rows in result, as expected because in this case LIKE looks for an exact match with the whole field.

If I run your second statement SELECT * FROM test t WHERE Note LIKE "Hello:%" I get one row back:

```<code>ID Note
-- ---------
1  Hello: it's a test!
</code>```

Are you sure you have setup the table right for FULLTEXT indexing?

First of all your Table engine must be an MyISAM table. Then you need to create an index (Indices) for your column (in my case Note) of the FULLTEXT type.

Title: mysql fulltext search and special chars

Body:
This might be far to late but I can't reproduce your problem.

I have a table with your two entries:

Table: Test
ID Note
-- ---------
1  Hello: it's a test!
2  Hello i am also a test!

If I run your first search SELECT * FROM test t WHERE Note LIKE "Hello:" I get 0 rows in result, as expected because in this case LIKE looks for an exact match with the whole field.

If I run your second statement SELECT * FROM test t WHERE Note LIKE "Hello:%" I get one row back:

ID Note
-- ---------
1  Hello: it's a test!

Are you sure you have setup the table right for FULLTEXT indexing?

First of all your Table engine must be an MyISAM table. Then you need to create an index (Indices) for your column (in my case Note) of the FULLTEXT type.