问:
Reasons for MovieClip to ignore Timeline code AS3
I have a custom class that is extended from MovieClip.  The class is basically creating a button that uses frame labels in the MovieClip to move between button states as mouse events are dispatched.  Each state (each approx 20 frames long) is terminated with a timeline stop().

This class has been used in numerous other projects, but after a certain point in my current application any buttons created as an extension of my button class stop executing the code on the timeline, and just play on a loop.  This includes any traces put into the timeline, but all code in the class still executes correctly, even the gotoAndPlay calls when the button state changes.

The strangest part is that no error is thrown by any of the misbehaving button instances on the stage.

What I need are suggestions of what could prevent any object that extends a certain class from executing timeline code without throwing an error.

Thanks!

UPDATE: This still has me stumped.  Our projects usually come in three parts: a lightweight preloader, a language and age gate, then the main application.  Each is loaded into the previous, each time using the current application domain.  After the main application has been loaded, any custom display object that extends MovieClip (directly or indirectly) will ignore any actionscript directly on its timeline.  The playhead can still be controlled though the class however.

UPDATE 2:  This is the code in the test button class that I have made.  Notice how there is nothing in it.

```<code>package com.test
{
    import flash.display.MovieClip;

    public class TestLabelButton extends MovieClip
    {
        public function TestLabelButton():void
        {

        }
    }
}
</code>```

Update 3:  So I've narrowed it down, but it's strange.  It seems that I can load my language gate into the preloader just fine, with the language gate being an swf with a custom document class that extends MovieClip. After that though, if I load any more SWFs that contain a custom doc class extending MovieClip it's like all subsequently instantiated MovieClips of extentions thereof loose all the code on their timelines.

答:
I'm not sure I fully understand your issue, but this sounds incredibly familiar to a problem I had in the past. I do the same thing. I never use Button symbols and always opt to use a MovieClip instead, since they're more flexible and having all your button state animations immediately exposed I find a much more intuitive way of working.

Any way, make sure that whatever frame you're calling via a frame label / name doesn't have a stop() on that frame. I've made that mistake a couple of times, where I have a fRollOver frame label at the start of a rollOver animation, and when you gotoAndPlay("fRollOver"), it just does nothing.

Another thing I've found is, and I've experienced this numerous times, that if you have a stop() immediately on the first frame, sometimes things brake. Flash just doesn't like it sometimes, and I can't explain this. It certainly works on almost all my projects. It might be a Flash version issue.

Body:
I have a custom class that is extended from MovieClip.  The class is basically creating a button that uses frame labels in the MovieClip to move between button states as mouse events are dispatched.  Each state (each approx 20 frames long) is terminated with a timeline stop().

This class has been used in numerous other projects, but after a certain point in my current application any buttons created as an extension of my button class stop executing the code on the timeline, and just play on a loop.  This includes any traces put into the timeline, but all code in the class still executes correctly, even the gotoAndPlay calls when the button state changes.

The strangest part is that no error is thrown by any of the misbehaving button instances on the stage.

What I need are suggestions of what could prevent any object that extends a certain class from executing timeline code without throwing an error.

Thanks!

UPDATE: This still has me stumped.  Our projects usually come in three parts: a lightweight preloader, a language and age gate, then the main application.  Each is loaded into the previous, each time using the current application domain.  After the main application has been loaded, any custom display object that extends MovieClip (directly or indirectly) will ignore any actionscript directly on its timeline.  The playhead can still be controlled though the class however.

UPDATE 2:  This is the code in the test button class that I have made.  Notice how there is nothing in it.

package com.test
{
    import flash.display.MovieClip;

    public class TestLabelButton extends MovieClip
    {
        public function TestLabelButton():void
        {

        }
    }
}

Update 3:  So I've narrowed it down, but it's strange.  It seems that I can load my language gate into the preloader just fine, with the language gate being an swf with a custom document class that extends MovieClip. After that though, if I load any more SWFs that contain a custom doc class extending MovieClip it's like all subsequently instantiated MovieClips of extentions thereof loose all the code on their timelines.


来源: stackexchange

问:
Python multiprocessing using pool.map with list
I am working on python code using multiprocessing. Below is the code

```<code>import multiprocessing
import os

def square(n):
    #logger.info("Worker process id for {0}: {1}".format(n, os.getpid()))
    logger.info("Evaluating square of the number {0}".format(n))
    print('process id of {0}: {1}'.format(n,os.getpid()))
    return (n * n)

if __name__ == "__main__":
    # input list
    mylist = [1, 2, 3, 4, 5,6,7,8,9,10]

    # creating a pool object
    p = multiprocessing.Pool(4)

    # map list to target function
    result = p.map(square, mylist)

    print(result)
</code>```

The number of CPU cores in my server is 4. If I use 4 only single processes is initiated. In general, it should start 4 separate processes right?.

If I set the value to 8 in the Pool object below is the response I got

```<code>process id of 1: 25872

process id of 2: 8132

process id of 3: 1672

process id of 4: 27000

process id of 6: 25872

process id of 5: 20964

process id of 9: 25872

process id of 8: 1672

process id of 7: 8132

process id of 10: 27000

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
</code>```

This started 5 separate processes(25872,8132,1672,27000,20964) even though there are only 4 cpu cores.

I don't understand why the pool initiated only 1 process when the value is 4 and initiated 5 separate processes when the value is 8.

Can pool object be instantiated with a value greater than the number of CPU cores?

Also what should be the optimal value we should use while instantiating pool object if a list contains a million records?

I have been through official python documentation, but I couldn't find info.
Please help

答:
Let's answer one by one.

I don't understand why the pool initiated only 1 process when the value is 4 and initiated 5 separate processes when the value is 8.

The pool initiated 4 processes. Do not mistake the number of cores you have for the number of processes, is totally independent. You have 5 processes because the initial python one also counts.
So, you started with the main python processes, which call the pool to start another 4 ones, that makes 5 of them.
In the case that you see that only a few of the processes are being used, it means that probably they are capable of killing the task fast enough so the other processes are not needed.

Can pool object be instantiated with a value greater than the number of CPU cores?

Yes indeed, you can instantiate any number you want (although there may be some kind of limit depending on the OS). But notice that this will just make your CPU to be overloaded. More explanation below.

Also what should be the optimal value we should use while instantiating pool object if a list contains a million records?

Well, usually the "optimal" would be that all the cores of your CPU are fully in usage by your pool. So, if you have 4 cores, 4 processes would be the best option, although sometimes this is not exactly like that it is a good starting approximation.

One last note,

I have been through official python documentation, but I couldn't find
  info.

This is not really python specific, it is general behavior in CS.

ContentLicense: CC BY-SA 4.0

Body:
I am working on python code using multiprocessing. Below is the code

import multiprocessing
import os

def square(n):
    #logger.info("Worker process id for {0}: {1}".format(n, os.getpid()))
    logger.info("Evaluating square of the number {0}".format(n))
    print('process id of {0}: {1}'.format(n,os.getpid()))
    return (n * n)

if __name__ == "__main__":
    # input list
    mylist = [1, 2, 3, 4, 5,6,7,8,9,10]

    # creating a pool object
    p = multiprocessing.Pool(4)

    # map list to target function
    result = p.map(square, mylist)

    print(result)

The number of CPU cores in my server is 4. If I use 4 only single processes is initiated. In general, it should start 4 separate processes right?.

If I set the value to 8 in the Pool object below is the response I got

process id of 1: 25872

process id of 2: 8132

process id of 3: 1672

process id of 4: 27000

process id of 6: 25872

process id of 5: 20964

process id of 9: 25872

process id of 8: 1672

process id of 7: 8132

process id of 10: 27000

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

This started 5 separate processes(25872,8132,1672,27000,20964) even though there are only 4 cpu cores.

I don't understand why the pool initiated only 1 process when the value is 4 and initiated 5 separate processes when the value is 8.

Can pool object be instantiated with a value greater than the number of CPU cores?

Also what should be the optimal value we should use while instantiating pool object if a list contains a million records?

I have been through official python documentation, but I couldn't find info.
Please help


问:
Open excel file in Tkinter and plot graphs
I've just started writing Python a month ago and now getting into Tkinter. I'm trying to build a program that a user can open an excel file into Tkinter, display the dataframe and the user can choose a certain graph type, insert the variables for the X-axis and Y-axis and plot it. I've build the general layout of the GUI using PAGE but having problems on how to give commands to the widgets on displaying the dataframe and plotting the graph.

Here's my code for the GUI:

```<code>import sys
from tkinter.filedialog import askopenfilename

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

try:
    import ttk
    py3 = 0
except ImportError:
    import tkinter.ttk as ttk
    py3 = 1

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = Tk()
    top = New_Toplevel_1 (root)
    root.mainloop()

w = None
def create_New_Toplevel_1(root, *args, **kwargs):
    '''Starting point when module is imported by another program.'''
    global w, w_win, rt
    rt = root
    w = Toplevel (root)
    top = New_Toplevel_1 (w)
    return (w, top)

def destroy_New_Toplevel_1():
    global w
    w.destroy()
    w = None

class New_Toplevel_1:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        self._bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        self._fgcolor = '#000000'  # X11 color: 'black'
        self._compcolor = '#d9d9d9' # X11 color: 'gray85'
        self._ana1color = '#d9d9d9' # X11 color: 'gray85'
        self._ana2color = '#d9d9d9' # X11 color: 'gray85'

        top.geometry("757x1037+832+67")
        top.title("New Toplevel 1")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")

        self.Canvas1 = Canvas(top)
        self.Canvas1.place(relx=0.04, rely=0.58, relheight=0.4, relwidth=0.92)
        self.Canvas1.configure(background="white")
        self.Canvas1.configure(borderwidth="2")
        self.Canvas1.configure(highlightbackground="#d9d9d9")
        self.Canvas1.configure(highlightcolor="black")
        self.Canvas1.configure(insertbackground="black")
        self.Canvas1.configure(relief=RIDGE)
        self.Canvas1.configure(selectbackground="#c4c4c4")
        self.Canvas1.configure(selectforeground="black")
        self.Canvas1.configure(width=695)

        self.Button2 = Button(top)
        self.Button2.place(relx=0.75, rely=0.52, height=42, width=138)
        self.Button2.configure(activebackground="#d9d9d9")
        self.Button2.configure(activeforeground="#000000")
        self.Button2.configure(background="#d9d9d9")
        self.Button2.configure(disabledforeground="#a3a3a3")
        self.Button2.configure(foreground="#000000")
        self.Button2.configure(highlightbackground="#d9d9d9")
        self.Button2.configure(highlightcolor="black")
        self.Button2.configure(pady="0")
        self.Button2.configure(text='''Generate Graph''')

        self.Labelframe1 = LabelFrame(top)
        self.Labelframe1.place(relx=0.05, rely=0.39, relheight=0.18
                , relwidth=0.44)
        self.Labelframe1.configure(relief=GROOVE)
        self.Labelframe1.configure(foreground="black")
        self.Labelframe1.configure(text='''Type of Graph''')
        self.Labelframe1.configure(background="#d9d9d9")
        self.Labelframe1.configure(highlightbackground="#d9d9d9")
        self.Labelframe1.configure(highlightcolor="black")
        self.Labelframe1.configure(width=330)

        self.Radiobutton1 = Radiobutton(self.Labelframe1)
        self.Radiobutton1.place(relx=0.06, rely=0.22, relheight=0.2
                , relwidth=0.31)
        self.Radiobutton1.configure(activebackground="#d9d9d9")
        self.Radiobutton1.configure(activeforeground="#000000")
        self.Radiobutton1.configure(background="#d9d9d9")
        self.Radiobutton1.configure(disabledforeground="#a3a3a3")
        self.Radiobutton1.configure(foreground="#000000")
        self.Radiobutton1.configure(highlightbackground="#d9d9d9")
        self.Radiobutton1.configure(highlightcolor="black")
        self.Radiobutton1.configure(justify=LEFT)
        self.Radiobutton1.configure(text='''Bar Chart''')

        self.Radiobutton2 = Radiobutton(self.Labelframe1)
        self.Radiobutton2.place(relx=0.06, rely=0.38, relheight=0.2
                , relwidth=0.35)
        self.Radiobutton2.configure(activebackground="#d9d9d9")
        self.Radiobutton2.configure(activeforeground="#000000")
        self.Radiobutton2.configure(background="#d9d9d9")
        self.Radiobutton2.configure(disabledforeground="#a3a3a3")
        self.Radiobutton2.configure(foreground="#000000")
        self.Radiobutton2.configure(highlightbackground="#d9d9d9")
        self.Radiobutton2.configure(highlightcolor="black")
        self.Radiobutton2.configure(justify=LEFT)
        self.Radiobutton2.configure(text='''Histogram''')

        self.Radiobutton3 = Radiobutton(self.Labelframe1)
        self.Radiobutton3.place(relx=0.06, rely=0.54, relheight=0.2
                , relwidth=0.37)
        self.Radiobutton3.configure(activebackground="#d9d9d9")
        self.Radiobutton3.configure(activeforeground="#000000")
        self.Radiobutton3.configure(background="#d9d9d9")
        self.Radiobutton3.configure(disabledforeground="#a3a3a3")
        self.Radiobutton3.configure(foreground="#000000")
        self.Radiobutton3.configure(highlightbackground="#d9d9d9")
        self.Radiobutton3.configure(highlightcolor="black")
        self.Radiobutton3.configure(justify=LEFT)
        self.Radiobutton3.configure(text='''Scatter Plot''')

        self.Button3 = Button(top)
        self.Button3.place(relx=0.28, rely=0.05, height=52, width=122)
        self.Button3.configure(activebackground="#d9d9d9")
        self.Button3.configure(activeforeground="#000000")
        self.Button3.configure(background="#d9d9d9")
        self.Button3.configure(disabledforeground="#a3a3a3")
        self.Button3.configure(foreground="#000000")
        self.Button3.configure(highlightbackground="#d9d9d9")
        self.Button3.configure(highlightcolor="black")
        self.Button3.configure(pady="0")
        self.Button3.configure(text='''Browse''')
        self.Button3.configure(width=122)
        self.Button3.configure(command=askopenfilename)

        self.Label5 = Label(top)
        self.Label5.place(relx=0.03, rely=0.06, height=31, width=147)
        self.Label5.configure(activebackground="#f9f9f9")
        self.Label5.configure(activeforeground="black")
        self.Label5.configure(background="#d9d9d9")
        self.Label5.configure(disabledforeground="#a3a3a3")
        self.Label5.configure(foreground="#000000")
        self.Label5.configure(highlightbackground="#d9d9d9")
        self.Label5.configure(highlightcolor="black")
        self.Label5.configure(text='''Upload File:''')
        self.Label5.configure(width=147)

        self.Label3 = Label(top)
        self.Label3.place(relx=0.05, rely=0.13, height=31, width=111)
        self.Label3.configure(background="#d9d9d9")
        self.Label3.configure(disabledforeground="#a3a3a3")
        self.Label3.configure(foreground="#000000")
        self.Label3.configure(text='''Data Frame :''')

        self.Text1 = Text(top)
        self.Text1.place(relx=0.05, rely=0.16, relheight=0.21, relwidth=0.9)
        self.Text1.configure(background="white")
        self.Text1.configure(font="TkTextFont")
        self.Text1.configure(foreground="black")
        self.Text1.configure(highlightbackground="#d9d9d9")
        self.Text1.configure(highlightcolor="black")
        self.Text1.configure(insertbackground="black")
        self.Text1.configure(selectbackground="#c4c4c4")
        self.Text1.configure(selectforeground="black")
        self.Text1.configure(width=684)
        self.Text1.configure(wrap=WORD)

        self.Labelframe2 = LabelFrame(top)
        self.Labelframe2.place(relx=0.5, rely=0.39, relheight=0.12
                , relwidth=0.45)
        self.Labelframe2.configure(relief=GROOVE)
        self.Labelframe2.configure(foreground="black")
        self.Labelframe2.configure(text='''Labelframe''')
        self.Labelframe2.configure(background="#d9d9d9")
        self.Labelframe2.configure(width=340)

        self.Label1 = Label(self.Labelframe2)
        self.Label1.place(relx=0.03, rely=0.24, height=31, width=67)
        self.Label1.configure(background="#d9d9d9")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(text='''X-axis :''')

        self.Label2 = Label(self.Labelframe2)
        self.Label2.place(relx=0.03, rely=0.56, height=31, width=66)
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(text='''Y-axis :''')

        self.Entry1 = Entry(self.Labelframe2)
        self.Entry1.place(relx=0.24, rely=0.24, relheight=0.29, relwidth=0.72)
        self.Entry1.configure(background="white")
        self.Entry1.configure(disabledforeground="#a3a3a3")
        self.Entry1.configure(font="TkFixedFont")
        self.Entry1.configure(foreground="#000000")
        self.Entry1.configure(insertbackground="black")
        self.Entry1.configure(width=244)

        self.Entry2 = Entry(self.Labelframe2)
        self.Entry2.place(relx=0.24, rely=0.56, relheight=0.29, relwidth=0.72)
        self.Entry2.configure(background="white")
        self.Entry2.configure(disabledforeground="#a3a3a3")
        self.Entry2.configure(font="TkFixedFont")
        self.Entry2.configure(foreground="#000000")
        self.Entry2.configure(insertbackground="black")
        self.Entry2.configure(width=244)

if __name__ == '__main__':
    vp_start_gui()
</code>```

I know how to save the data into a dataframe and plot graphs in Python, but i'm not sure where to write those codes when GUI is involved. All i was able to do was give a command to the 'Browse' button to search for the excel file.

```<code>self.Button3.configure(command=askopenfilename)
</code>```

Can someone help me:

How to save the excel file chosen from the command into a dataframe

How to display the dataframe into the textbox below

How to plot the graph with the criteria (type of graph and axes) chosen onto the canvas at bottom

Thanks so much in advance.

答:
```<code>import tkinter as tk
from tkinter import filedialog
import pandas as pd
import matplotlib.pyplot as plt

root= tk.Tk()

canvas1 = tk.Canvas(root, width = 300, height = 300, bg = 'lightsteelblue')
canvas1.pack()

def getExcel ():
    global df

    import_file_path = filedialog.askopenfilename()
    df = pd.read_excel (import_file_path)
    df["Year"] = pd.to_datetime(df["Year"], format="%Y")
    ax = df.plot("Year", "Accidents",marker='o',color='r')
    plt.grid()
    plt.title('Yearly Graph')
    ax.figure.autofmt_xdate()
    plt.show()

browseButton_Excel = tk.Button(text='Import Excel File', command=getExcel, bg='green', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 150, window=browseButton_Excel)

root.mainloop()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've just started writing Python a month ago and now getting into Tkinter. I'm trying to build a program that a user can open an excel file into Tkinter, display the dataframe and the user can choose a certain graph type, insert the variables for the X-axis and Y-axis and plot it. I've build the general layout of the GUI using PAGE but having problems on how to give commands to the widgets on displaying the dataframe and plotting the graph.

Here's my code for the GUI:

import sys
from tkinter.filedialog import askopenfilename

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

try:
    import ttk
    py3 = 0
except ImportError:
    import tkinter.ttk as ttk
    py3 = 1

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = Tk()
    top = New_Toplevel_1 (root)
    root.mainloop()

w = None
def create_New_Toplevel_1(root, *args, **kwargs):
    '''Starting point when module is imported by another program.'''
    global w, w_win, rt
    rt = root
    w = Toplevel (root)
    top = New_Toplevel_1 (w)
    return (w, top)

def destroy_New_Toplevel_1():
    global w
    w.destroy()
    w = None

class New_Toplevel_1:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        self._bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        self._fgcolor = '#000000'  # X11 color: 'black'
        self._compcolor = '#d9d9d9' # X11 color: 'gray85'
        self._ana1color = '#d9d9d9' # X11 color: 'gray85'
        self._ana2color = '#d9d9d9' # X11 color: 'gray85'

        top.geometry("757x1037+832+67")
        top.title("New Toplevel 1")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")

        self.Canvas1 = Canvas(top)
        self.Canvas1.place(relx=0.04, rely=0.58, relheight=0.4, relwidth=0.92)
        self.Canvas1.configure(background="white")
        self.Canvas1.configure(borderwidth="2")
        self.Canvas1.configure(highlightbackground="#d9d9d9")
        self.Canvas1.configure(highlightcolor="black")
        self.Canvas1.configure(insertbackground="black")
        self.Canvas1.configure(relief=RIDGE)
        self.Canvas1.configure(selectbackground="#c4c4c4")
        self.Canvas1.configure(selectforeground="black")
        self.Canvas1.configure(width=695)

        self.Button2 = Button(top)
        self.Button2.place(relx=0.75, rely=0.52, height=42, width=138)
        self.Button2.configure(activebackground="#d9d9d9")
        self.Button2.configure(activeforeground="#000000")
        self.Button2.configure(background="#d9d9d9")
        self.Button2.configure(disabledforeground="#a3a3a3")
        self.Button2.configure(foreground="#000000")
        self.Button2.configure(highlightbackground="#d9d9d9")
        self.Button2.configure(highlightcolor="black")
        self.Button2.configure(pady="0")
        self.Button2.configure(text='''Generate Graph''')

        self.Labelframe1 = LabelFrame(top)
        self.Labelframe1.place(relx=0.05, rely=0.39, relheight=0.18
                , relwidth=0.44)
        self.Labelframe1.configure(relief=GROOVE)
        self.Labelframe1.configure(foreground="black")
        self.Labelframe1.configure(text='''Type of Graph''')
        self.Labelframe1.configure(background="#d9d9d9")
        self.Labelframe1.configure(highlightbackground="#d9d9d9")
        self.Labelframe1.configure(highlightcolor="black")
        self.Labelframe1.configure(width=330)

        self.Radiobutton1 = Radiobutton(self.Labelframe1)
        self.Radiobutton1.place(relx=0.06, rely=0.22, relheight=0.2
                , relwidth=0.31)
        self.Radiobutton1.configure(activebackground="#d9d9d9")
        self.Radiobutton1.configure(activeforeground="#000000")
        self.Radiobutton1.configure(background="#d9d9d9")
        self.Radiobutton1.configure(disabledforeground="#a3a3a3")
        self.Radiobutton1.configure(foreground="#000000")
        self.Radiobutton1.configure(highlightbackground="#d9d9d9")
        self.Radiobutton1.configure(highlightcolor="black")
        self.Radiobutton1.configure(justify=LEFT)
        self.Radiobutton1.configure(text='''Bar Chart''')

        self.Radiobutton2 = Radiobutton(self.Labelframe1)
        self.Radiobutton2.place(relx=0.06, rely=0.38, relheight=0.2
                , relwidth=0.35)
        self.Radiobutton2.configure(activebackground="#d9d9d9")
        self.Radiobutton2.configure(activeforeground="#000000")
        self.Radiobutton2.configure(background="#d9d9d9")
        self.Radiobutton2.configure(disabledforeground="#a3a3a3")
        self.Radiobutton2.configure(foreground="#000000")
        self.Radiobutton2.configure(highlightbackground="#d9d9d9")
        self.Radiobutton2.configure(highlightcolor="black")
        self.Radiobutton2.configure(justify=LEFT)
        self.Radiobutton2.configure(text='''Histogram''')

        self.Radiobutton3 = Radiobutton(self.Labelframe1)
        self.Radiobutton3.place(relx=0.06, rely=0.54, relheight=0.2
                , relwidth=0.37)
        self.Radiobutton3.configure(activebackground="#d9d9d9")
        self.Radiobutton3.configure(activeforeground="#000000")
        self.Radiobutton3.configure(background="#d9d9d9")
        self.Radiobutton3.configure(disabledforeground="#a3a3a3")
        self.Radiobutton3.configure(foreground="#000000")
        self.Radiobutton3.configure(highlightbackground="#d9d9d9")
        self.Radiobutton3.configure(highlightcolor="black")
        self.Radiobutton3.configure(justify=LEFT)
        self.Radiobutton3.configure(text='''Scatter Plot''')

        self.Button3 = Button(top)
        self.Button3.place(relx=0.28, rely=0.05, height=52, width=122)
        self.Button3.configure(activebackground="#d9d9d9")
        self.Button3.configure(activeforeground="#000000")
        self.Button3.configure(background="#d9d9d9")
        self.Button3.configure(disabledforeground="#a3a3a3")
        self.Button3.configure(foreground="#000000")
        self.Button3.configure(highlightbackground="#d9d9d9")
        self.Button3.configure(highlightcolor="black")
        self.Button3.configure(pady="0")
        self.Button3.configure(text='''Browse''')
        self.Button3.configure(width=122)
        self.Button3.configure(command=askopenfilename)

        self.Label5 = Label(top)
        self.Label5.place(relx=0.03, rely=0.06, height=31, width=147)
        self.Label5.configure(activebackground="#f9f9f9")
        self.Label5.configure(activeforeground="black")
        self.Label5.configure(background="#d9d9d9")
        self.Label5.configure(disabledforeground="#a3a3a3")
        self.Label5.configure(foreground="#000000")
        self.Label5.configure(highlightbackground="#d9d9d9")
        self.Label5.configure(highlightcolor="black")
        self.Label5.configure(text='''Upload File:''')
        self.Label5.configure(width=147)

        self.Label3 = Label(top)
        self.Label3.place(relx=0.05, rely=0.13, height=31, width=111)
        self.Label3.configure(background="#d9d9d9")
        self.Label3.configure(disabledforeground="#a3a3a3")
        self.Label3.configure(foreground="#000000")
        self.Label3.configure(text='''Data Frame :''')

        self.Text1 = Text(top)
        self.Text1.place(relx=0.05, rely=0.16, relheight=0.21, relwidth=0.9)
        self.Text1.configure(background="white")
        self.Text1.configure(font="TkTextFont")
        self.Text1.configure(foreground="black")
        self.Text1.configure(highlightbackground="#d9d9d9")
        self.Text1.configure(highlightcolor="black")
        self.Text1.configure(insertbackground="black")
        self.Text1.configure(selectbackground="#c4c4c4")
        self.Text1.configure(selectforeground="black")
        self.Text1.configure(width=684)
        self.Text1.configure(wrap=WORD)

        self.Labelframe2 = LabelFrame(top)
        self.Labelframe2.place(relx=0.5, rely=0.39, relheight=0.12
                , relwidth=0.45)
        self.Labelframe2.configure(relief=GROOVE)
        self.Labelframe2.configure(foreground="black")
        self.Labelframe2.configure(text='''Labelframe''')
        self.Labelframe2.configure(background="#d9d9d9")
        self.Labelframe2.configure(width=340)

        self.Label1 = Label(self.Labelframe2)
        self.Label1.place(relx=0.03, rely=0.24, height=31, width=67)
        self.Label1.configure(background="#d9d9d9")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(text='''X-axis :''')

        self.Label2 = Label(self.Labelframe2)
        self.Label2.place(relx=0.03, rely=0.56, height=31, width=66)
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(text='''Y-axis :''')

        self.Entry1 = Entry(self.Labelframe2)
        self.Entry1.place(relx=0.24, rely=0.24, relheight=0.29, relwidth=0.72)
        self.Entry1.configure(background="white")
        self.Entry1.configure(disabledforeground="#a3a3a3")
        self.Entry1.configure(font="TkFixedFont")
        self.Entry1.configure(foreground="#000000")
        self.Entry1.configure(insertbackground="black")
        self.Entry1.configure(width=244)

        self.Entry2 = Entry(self.Labelframe2)
        self.Entry2.place(relx=0.24, rely=0.56, relheight=0.29, relwidth=0.72)
        self.Entry2.configure(background="white")
        self.Entry2.configure(disabledforeground="#a3a3a3")
        self.Entry2.configure(font="TkFixedFont")
        self.Entry2.configure(foreground="#000000")
        self.Entry2.configure(insertbackground="black")
        self.Entry2.configure(width=244)

if __name__ == '__main__':
    vp_start_gui()

I know how to save the data into a dataframe and plot graphs in Python, but i'm not sure where to write those codes when GUI is involved. All i was able to do was give a command to the 'Browse' button to search for the excel file.

self.Button3.configure(command=askopenfilename)

Can someone help me:

How to save the excel file chosen from the command into a dataframe

How to display the dataframe into the textbox below

How to plot the graph with the criteria (type of graph and axes) chosen onto the canvas at bottom

Thanks so much in advance.


问:
How to use value from any element in my node js program?
```<code>Element (<input id="pagenum-input" class="form-control" aria-label="..." value="1" min="1" max="28">)
</code>```

I want to use the Value of max(28) as value of variable maximum that i have created in 2nd loop. How i can get the value of max from input tag to my program?
Any help would be appreciated. Thanks !

```<code>const puppeteer = require('puppeteer');

async function getPic() {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();

  for (let j=2; j<=6; j++) {
    await page.setViewport({width: 2000, height: 2500})
    await page.goto('http://epaper.freepressjournal.in/');
    await page.click('body > div > div.common_section > div > div > div.rw_rightcrousel > div > div:nth-child('+j+') > a > div > img');
    await page.waitFor(2000);
    await page.click('#left-chunk-1 > img');
    var maximum;
    for (let i= 1; i<=maximum; i++) {
      await page.waitFor(2000);
      await page.screenshot({path: '//192.168.2.19/em/automatic downloading/Puppeteer/freepressjournal/'+j+''+i+'.png'});
      await page.waitFor(2000);
      await page.click('#page-div > a.right_arrow_pgright.btn_next');
    }
  }

  await browser.close();
}

getPic();

// This loop will automatically get the value of max that is 28.
// The value of max will vary according to pages. The program should accept
// the value of max in maximum and run the loop accordingly.
for (let i= 1; i<=maximum; i++)
</code>```

答:
You can interact with any element on the page with the help of page.evaluate function. Here's how you can find the input element of interest and access one of its attributes:

```<code>var maximum = await page.evaluate(() => {
    return document.getElementById("pagenum-input").getAttribute("max");
});
</code>```

Body:
Element (<input id="pagenum-input" class="form-control" aria-label="..." value="1" min="1" max="28">)

I want to use the Value of max(28) as value of variable maximum that i have created in 2nd loop. How i can get the value of max from input tag to my program?
Any help would be appreciated. Thanks !

const puppeteer = require('puppeteer');

async function getPic() {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();

  for (let j=2; j<=6; j++) {
    await page.setViewport({width: 2000, height: 2500})
    await page.goto('http://epaper.freepressjournal.in/');
    await page.click('body > div > div.common_section > div > div > div.rw_rightcrousel > div > div:nth-child('+j+') > a > div > img');
    await page.waitFor(2000);
    await page.click('#left-chunk-1 > img');
    var maximum;
    for (let i= 1; i<=maximum; i++) {
      await page.waitFor(2000);
      await page.screenshot({path: '//192.168.2.19/em/automatic downloading/Puppeteer/freepressjournal/'+j+''+i+'.png'});
      await page.waitFor(2000);
      await page.click('#page-div > a.right_arrow_pgright.btn_next');
    }
  }

  await browser.close();
}

getPic();

// This loop will automatically get the value of max that is 28.
// The value of max will vary according to pages. The program should accept
// the value of max in maximum and run the loop accordingly.
for (let i= 1; i<=maximum; i++)

Body:
You can interact with any element on the page with the help of page.evaluate function. Here's how you can find the input element of interest and access one of its attributes:

var maximum = await page.evaluate(() => {
    return document.getElementById("pagenum-input").getAttribute("max");
});


问:
can't access inner class's public variable... which is inherited from parent
Java Q: I can't access a public variable in my parent's class' inner class called foo. Why? setup is next(pseudo coded for brevity):</p>

```<code>public class PageObject
{
    public class Button
    {
        public String foo ="I want this string."  //can't access....
    }
    ....other stuff I can access here...
}

public class worker
    {
    public PageObject p = new PageObject();
    }

public class workerchild extends worker
{
    p.Buttons.    <---don't have access to Buttons public variables, only .class, etc.
}
</code>```

答:
p.Button is a classname.

Like any other classname, it can only be used to access static members.

You need to get an instance of the Button class. (eg, p.new Button().foo)

Body:
Java Q: I can't access a public variable in my parent's class' inner class called foo. Why? setup is next(pseudo coded for brevity):

public class PageObject
{
    public class Button
    {
        public String foo ="I want this string."  //can't access....
    }
    ....other stuff I can access here...
}

public class worker
    {
    public PageObject p = new PageObject();
    }

public class workerchild extends worker
{
    p.Buttons.    <---don't have access to Buttons public variables, only .class, etc.
}


问:
Changing iPhone X status bar style color to white
I need to change the status bar content color to white in my iPhone project.

I have done this by

```<code>override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
</code>```

This changes the color but there is one problem. On iPhone X the time on the top left is getting truncated. Any idea how to fix this?

答:
Usually these types of issues arise because of date time format. Can you please check your settings app, in particular General->International and General->Date & Time and by changing those settings and see the behavior.

Besides these its necessary to take a look of your code, if you have any customization for status bar except color.

Body:
I need to change the status bar content color to white in my iPhone project.

I have done this by

override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

This changes the color but there is one problem. On iPhone X the time on the top left is getting truncated. Any idea how to fix this?


问:
Describing the first few evaluation steps of a given foldr function
The following function is given:

```<code>mystery a b c xs =
  foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs a b
</code>```

I know what the function does roughly but I have a hard time really understanding the intermediate steps. I picked following example:

```<code>mystery 1 2 3 [1, 2, 3]
</code>```

Especially the use of rec is giving me a hard time. I assume that one of the final steps looks like this:

```<code>(\a b -> 3 + (b + 3 + 3 + 3) - 3) [] 1 2
</code>```

So the output is 11. Could someone describe the first few steps of the execution? What happens after:

```<code>foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [1, 2, 3] 1 2
</code>```

答:
Substituting the definition for foldr, the function reveals itself to be

```<code>mystery a b c xs =
 = foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs a b
 = let { g x r   a b =  r   x (b + c); z a b =  a + b - c } in
     foldr g z xs a b
     =>  foldr g z [] a b = z a b            = a  + b       - c
     =>  foldr g z [x1,x2,...,xn] a  b
          = g x1 (foldr g z [x2,...,xn]) a b   -- g x r a b = r x (b+c)
          = foldr g z [x2,...,xn] x1 (b+c)
          = foldr g z [x3,...,xn] x2 (b+c*2)
          = foldr g z [         ] xn (b+c*n) = xn + b + c*n - c
 = last (a:xs) + b + c * (length xs - 1)
</code>```

Naming the two lambda functions, using short names, makes it much easier to handle the expressions visually.

Body:
The following function is given:

mystery a b c xs =
  foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs a b

I know what the function does roughly but I have a hard time really understanding the intermediate steps. I picked following example:

mystery 1 2 3 [1, 2, 3]

Especially the use of rec is giving me a hard time. I assume that one of the final steps looks like this:

(\a b -> 3 + (b + 3 + 3 + 3) - 3) [] 1 2

So the output is 11. Could someone describe the first few steps of the execution? What happens after:

foldr (\x rec a b -> rec x (b + 3)) (\a b -> a + b - 3) [1, 2, 3] 1 2

Body:
Substituting the definition for foldr, the function reveals itself to be

mystery a b c xs =
 = foldr (\x rec a b -> rec x (b + c)) (\a b -> a + b - c) xs a b
 = let { g x r   a b =  r   x (b + c); z a b =  a + b - c } in
     foldr g z xs a b
     =>  foldr g z [] a b = z a b            = a  + b       - c
     =>  foldr g z [x1,x2,...,xn] a  b
          = g x1 (foldr g z [x2,...,xn]) a b   -- g x r a b = r x (b+c)
          = foldr g z [x2,...,xn] x1 (b+c)
          = foldr g z [x3,...,xn] x2 (b+c*2)
          = foldr g z [         ] xn (b+c*n) = xn + b + c*n - c
 = last (a:xs) + b + c * (length xs - 1)

Naming the two lambda functions, using short names, makes it much easier to handle the expressions visually.


问:
Password field not taking keys using Selenium through Python
I am trying to send keys via selenium it is taking for username but not for password.

I have tried clicking and sending keys then.

HTML of password field:

```<code><div>
    <input name="txtPassword" type="password" id="txtPassword" required="" style="margin-bottom:0px;" class="blur">
    <a id="btnSmallForgotPassword" class="smallForgotPassword visible-sm-block" href="javascript:__doPostBack('btnSmallForgotPassword','')">forgot password</a>
</div>
</code>```

```<code>WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).click()
WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).send_keys("san")
</code>```

I am getting no error message but it is not sending keys for password

答:
try with this code :

```<code>WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.ID,"txtPassword"))).send_keys('your_password')
</code>```

You should not create object of WebDriverWait too many times, use it like this :

```<code>wait = WebDriverWait(driver,10)

wait.until(EC.element_to_be_clickable((By.ID,"txtPassword"))).click()
wait.until(EC.element_to_be_clickable((By.ID,"txtPassword"))).send_keys('your_password')
</code>```

and wait.until(EC.element_to_be_clickable((By.ID,"txtPassword"))) returns a web element, where you can use methods like click(), clear(), send_keys() etc.

You can write your code like this also :

```<code>password_field = wait.until(EC.element_to_be_clickable((By.ID,"txtPassword")))
password_field.click()
password_field.send_keys('your_password')
</code>```

EDIT1 :

You can use this css selector :

```<code>input[id='txtPassword']
</code>```

EDIT 2 :

You can use this full method :

```<code>wait = WebDriverWait(driver,10)

driver.maximize_window()
driver.get("http://backgriduk.medialava.com/pages/Staff/Login.aspx?LANGUAGE_ID=3&O=7")

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input[id='txtUser']"))).send_keys("abhishek")

wait.until(EC.element_to_be_clickable((By.ID,"txtPassword"))).click()
wait.until(EC.element_to_be_clickable((By.ID,"txtPassword"))).send_keys('your_password')
</code>```

Body:
I am trying to send keys via selenium it is taking for username but not for password.

I have tried clicking and sending keys then.

HTML of password field:

    <input name="txtPassword" type="password" id="txtPassword" required="" style="margin-bottom:0px;" class="blur">
    forgot password

WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).click()
WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).send_keys("san")

I am getting no error message but it is not sending keys for password

Body:
try with this code :

WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.ID,"txtPassword"))).send_keys('your_password')

You should not create object of WebDriverWait too many times, use it like this :

wait = WebDriverWait(driver,10)

wait.until(EC.element_to_be_clickable((By.ID,"txtPassword"))).click()
wait.until(EC.element_to_be_clickable((By.ID,"txtPassword"))).send_keys('your_password')

and wait.until(EC.element_to_be_clickable((By.ID,"txtPassword"))) returns a web element, where you can use methods like click(), clear(), send_keys() etc.

You can write your code like this also :

password_field = wait.until(EC.element_to_be_clickable((By.ID,"txtPassword")))
password_field.click()
password_field.send_keys('your_password')

EDIT1 :

You can use this css selector :

input[id='txtPassword']

EDIT 2 :

You can use this full method :

wait = WebDriverWait(driver,10)

driver.maximize_window()
driver.get("http://backgriduk.medialava.com/pages/Staff/Login.aspx?LANGUAGE_ID=3&O=7")

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input[id='txtUser']"))).send_keys("abhishek")

wait.until(EC.element_to_be_clickable((By.ID,"txtPassword"))).click()
wait.until(EC.element_to_be_clickable((By.ID,"txtPassword"))).send_keys('your_password')


问:
Smart pointers cannot be used as raw pointers automatically?
I'm trying to convert codes to use smart pointers instead of raw pointers.  But was wondering - is it really not possible for smart pointers to be used as raw pointers?

In this example:

```<code>#include <iostream>
#include <string>
#include <memory>

void printer(int* x)
{
    std::cout << "x = " << x << std::endl;
}

int main()
{
    auto x = std::make_unique<int>(5);
    printer(x);
    return 0;
}
</code>```

I get an error:

```<code>In function 'int main()': 14:14: error: cannot convert
'std::unique_ptr<int, std::default_delete<int> >' to 'int*' for argument '1'
to 'void printer(int*)'
</code>```

How should this be coded?  Thanks!

答:
There cannot be an implicit conversion because an implicit conversion doesn't have context to do the right thing. printer takes a non-owning pointer, but what about other functions that need to take ownership? For instance

```<code>void kill(int *p) { delete p; }
</code>```

Silently doing the conversion when calling kill(p); would be the wrong thing! It will lead to a double delete. The pointer has no way to know it should stop owning the object, it has to be told via a call to release. Anything else would be wrong.

Since smart pointers are all about enforcing explicit ownership semantics, the conversion to a raw pointer needs to be explicit too, and have a name that conveys how the ownership is affected.

Body:
I'm trying to convert codes to use smart pointers instead of raw pointers.  But was wondering - is it really not possible for smart pointers to be used as raw pointers?

In this example:

#include <iostream>
#include <string>
#include <memory>

void printer(int* x)
{
    std::cout << "x = " << x << std::endl;
}

int main()
{
    auto x = std::make_unique<int>(5);
    printer(x);
    return 0;
}

I get an error:

In function 'int main()': 14:14: error: cannot convert
'std::unique_ptr<int, std::default_delete<int> >' to 'int*' for argument '1'
to 'void printer(int*)'

How should this be coded?  Thanks!

Body:
There cannot be an implicit conversion because an implicit conversion doesn't have context to do the right thing. printer takes a non-owning pointer, but what about other functions that need to take ownership? For instance

void kill(int *p) { delete p; }

Silently doing the conversion when calling kill(p); would be the wrong thing! It will lead to a double delete. The pointer has no way to know it should stop owning the object, it has to be told via a call to release. Anything else would be wrong.

Since smart pointers are all about enforcing explicit ownership semantics, the conversion to a raw pointer needs to be explicit too, and have a name that conveys how the ownership is affected.


问:
How to convert a string to camel case in Mule 4
Is there any function to convert a string ex: "iamhuman" to camel case "iAmHuman" in Mule 4 application.</p>

答:
There is a camelize function you can use in dataweave. BUT it will NOT work with your example because it won't know where the word breaks are. If you had another separator, such as underscores or hyphens then this would work:

```<code>%dw 2.0
import * from dw::core::Strings
output application/json
---
{ "camelize" : camelize("i_am_human") }
</code>```

Body:
There is a camelize function you can use in dataweave. BUT it will NOT work with your example because it won't know where the word breaks are. If you had another separator, such as underscores or hyphens then this would work:

%dw 2.0
import * from dw::core::Strings
output application/json
---
{ "camelize" : camelize("i_am_human") }


问:
How to create an .IMG image of a disc (sd card) without including free space?
In Linux, we can do

```<code>dd if=/dev/sdb of=bckup.img
</code>```

but if the disk is of 32GB with only 4GB used, the 32GB image file is waste of space-time. Is there any way or tool to create images with only valid data?

答:
If you have a big SD card 16 GB, 32 GB etc but you want to save space with backup you can use:

```<code>sudo apt-get install gnome-disk-utility
</code>```

Open disk utility to check witch letter is your usb drive actually has:

```<code>gnome-disks
</code>```

In my case a 32GB SD card with Raspbian image on it recognised as: /dev/sde

So I run with /dev/sde:

```<code>sudo dd bs=4M status=progress if=/dev/sde | gzip > \
/you-selected-full-path-here/raspberry-images/`date +%Y%m%d`_rpi_image_backup.gz
</code>```

```<code>status=progress gives you progress bar indication
| gzip > compresses the 32 GB total size and not writing the empty space from the 32 GB
`date +%Y%m%d` writes today date in the filename
</code>```

Output: 20190529_rpi_image_backup.gz

And the size is only 3.5GB.
If you want to write this image to a new SD card use:

https://www.balena.io/etcher/

Also you can write this image made from 32 GB to a 16 GB or 8 GB disk, it is not complaining that the image is too large anymore.

Body:
In Linux, we can do

dd if=/dev/sdb of=bckup.img

but if the disk is of 32GB with only 4GB used, the 32GB image file is waste of space-time. Is there any way or tool to create images with only valid data?

Body:
If you have a big SD card 16 GB, 32 GB etc but you want to save space with backup you can use:

sudo apt-get install gnome-disk-utility

Open disk utility to check witch letter is your usb drive actually has:

gnome-disks

In my case a 32GB SD card with Raspbian image on it recognised as: /dev/sde

So I run with /dev/sde:

sudo dd bs=4M status=progress if=/dev/sde | gzip > \
/you-selected-full-path-here/raspberry-images/`date +%Y%m%d`_rpi_image_backup.gz

status=progress gives you progress bar indication
| gzip > compresses the 32 GB total size and not writing the empty space from the 32 GB
`date +%Y%m%d` writes today date in the filename

Output: 20190529_rpi_image_backup.gz

And the size is only 3.5GB.
If you want to write this image to a new SD card use:

https://www.balena.io/etcher/

Also you can write this image made from 32 GB to a 16 GB or 8 GB disk, it is not complaining that the image is too large anymore.


问:
Vue-router error: TypeError: Cannot read property 'matched' of undefined
I'm trying to write my first Vuejs app. I'm using vue-cli and simple-webpack boilerplate.

When I add vue-router links to my app component I get this error in console

Error in render function: "TypeError: Cannot read property 'matched' of undefined"

Here is my code:

App.vue

```<code><template>
  <div>
    <h2>Links</h2>
    <ul>
      <router-link to='/'>Home</router-link>
      <router-link to='/query'>Query</router-link>

      <router-view></router-view>
    </ul>
  </div>
</template>

<script>
    export default {}
</script>
</code>```

main.js

```<code>import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
import routes from './routes.js'
import App from './App.vue'

const app = new Vue({
  el: '#app',
  routes,
  render: h => h(App)
})
</code>```

routes.js

```<code>import VueRouter from 'vue-router';
let routes=[
  {
    path: '/',
    component: require('./Components/Home.vue')
  },
  {
    path: '/query',
    component: require('./Components/Query.vue')
  }
];

export default new VueRouter({routes});
</code>```

答:
vue & vue router & match bug & solution

match bugs

solution

name must be router

https://stackoverflow.com/a/44618867/5934465

OK

import default module bug

import default module no need {}!

Body:
I'm trying to write my first Vuejs app. I'm using vue-cli and simple-webpack boilerplate.

When I add vue-router links to my app component I get this error in console

Error in render function: "TypeError: Cannot read property 'matched' of undefined"

Here is my code:

App.vue

<template>

Links

      <router-link to='/'>Home</router-link>
      <router-link to='/query'>Query</router-link>

      <router-view></router-view>

</template>

main.js

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
import routes from './routes.js'
import App from './App.vue'

const app = new Vue({
  el: '#app',
  routes,
  render: h => h(App)
})

routes.js

import VueRouter from 'vue-router';
let routes=[
  {
    path: '/',
    component: require('./Components/Home.vue')
  },
  {
    path: '/query',
    component: require('./Components/Query.vue')
  }
];

export default new VueRouter({routes});


问:
Xml scale animation of ImageView makes the image aliased
I have a little xml animation that animates few ImageViews inside my layout. Actually it is the wavescale animation from the api demos sdk example. This animation scales the image up and then down to its original size so it looks sort of wave. The problem is when the image is upscaled it looks very bad, the edges are aliased and the image is blocky.
My animation looks like this:

```<code><set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">
    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:duration="100" />
    <scale
        android:fromXScale="0.5" android:toXScale="1.25"
        android:fromYScale="0.5" android:toYScale="1.25"
        android:pivotX="50%" android:pivotY="50%"
        android:duration="200" />
    <scale
        android:fromXScale="1.25" android:toXScale="1.0"
        android:fromYScale="1.25" android:toYScale="1.0"
        android:pivotX="50%" android:pivotY="50%"
        android:startOffset="200"
        android:duration="100" />
</set>
</code>```

I tried, instead of loading the image directly in the src of the ImageView, to wrap it in a xml bitmap element and enable antialiasing and filtering but it makes no difference.

```<code><?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/myimage_img"
    android:antialias="true"
    android:filter="true"
    android:tileMode="disabled"
/>
</code>```

And my ImageView looks like this:

```<code><ImageView android:src="@drawable/myimage" android:layout_height="wrap_content" android:layout_margin="5dp" android:adjustViewBounds="true" android:layout_width="fill_parent" android:scaleType="centerInside"></ImageView>
</code>```

Please also note that the image is not really upscaled. The image itself is bigger that it appears on the screen. It is centered inside the ImageView. But looks like the animation is not using the original image to render it with different size, but using the downscaled image from the ImageView and scaling it up again.

Can you please help me to make my image appear smooth when it is animated?

答: Do you have the proper image size based on your device DPI? Even though an image looks large on your PC screen, an image may be small on the phone's screen due to a larger number of dots per inch. If this is the case, Android will have to scale the image up.</p>

Body:
I have a little xml animation that animates few ImageViews inside my layout. Actually it is the wavescale animation from the api demos sdk example. This animation scales the image up and then down to its original size so it looks sort of wave. The problem is when the image is upscaled it looks very bad, the edges are aliased and the image is blocky.
My animation looks like this:

<set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator">
    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:duration="100" />
    <scale
        android:fromXScale="0.5" android:toXScale="1.25"
        android:fromYScale="0.5" android:toYScale="1.25"
        android:pivotX="50%" android:pivotY="50%"
        android:duration="200" />
    <scale
        android:fromXScale="1.25" android:toXScale="1.0"
        android:fromYScale="1.25" android:toYScale="1.0"
        android:pivotX="50%" android:pivotY="50%"
        android:startOffset="200"
        android:duration="100" />
</set>

I tried, instead of loading the image directly in the src of the ImageView, to wrap it in a xml bitmap element and enable antialiasing and filtering but it makes no difference.

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/myimage_img"
    android:antialias="true"
    android:filter="true"
    android:tileMode="disabled"
/>

And my ImageView looks like this:

<ImageView android:src="@drawable/myimage" android:layout_height="wrap_content" android:layout_margin="5dp" android:adjustViewBounds="true" android:layout_width="fill_parent" android:scaleType="centerInside"></ImageView>

Please also note that the image is not really upscaled. The image itself is bigger that it appears on the screen. It is centered inside the ImageView. But looks like the animation is not using the original image to render it with different size, but using the downscaled image from the ImageView and scaling it up again.

Can you please help me to make my image appear smooth when it is animated?


问:
ResNet: 100% accuracy during training, but 33% prediction accuracy with the same data
I am new to machine learning and deep learning, and for learning purposes I tried to play with Resnet. I tried to overfit over small data (3 different images) and see if I can get almost 0 loss and 1.0 accuracy - and I did.

The problem is that predictions on the training images (i.e. the same 3 images used for training) are not correct..

Training Images

Image labels

[1,0,0], [0,1,0], [0,0,1]

My python code

#loading 3 images and resizing them
imgs = np.array([np.array(Image.open("./Images/train/" + fname)
                          .resize((197, 197), Image.ANTIALIAS)) for fname in
                 os.listdir("./Images/train/")]).reshape(-1,197,197,1)
# creating labels
y = np.array([[1,0,0],[0,1,0],[0,0,1]])
# create resnet model
model = ResNet50(input_shape=(197, 197,1),classes=3,weights=None)

# compile & fit model
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['acc'])

model.fit(imgs,y,epochs=5,shuffle=True)

# predict on training data
print(model.predict(imgs))
```

<p>The model does overfit the data:</p>

<pre class="lang-python prettyprint-override"><code>3/3 [==============================] - 22s - loss: 1.3229 - acc: 0.0000e+00
Epoch 2/5
3/3 [==============================] - 0s - loss: 0.1474 - acc: 1.0000
Epoch 3/5
3/3 [==============================] - 0s - loss: 0.0057 - acc: 1.0000
Epoch 4/5
3/3 [==============================] - 0s - loss: 0.0107 - acc: 1.0000
Epoch 5/5
3/3 [==============================] - 0s - loss: 1.3815e-04 - acc: 1.0000
</code>```

but predictions are:

 [[  1.05677405e-08   9.99999642e-01   3.95520459e-07]
 [  1.11955103e-08   9.99999642e-01   4.14905685e-07]
 [  1.02637095e-07   9.99997497e-01   2.43751242e-06]]
```

which means that all images got label=[0,1,0]

why? and how can that happen?

答:
What happens is basically that keras.fit() i.e your

```<code>model.fit()
</code>```

is while having the best fit the precision is lost. As, the precision is lost the models fit gives problems and varied results.The keras.fit only has a good fit not the required precision

Body:
I am new to machine learning and deep learning, and for learning purposes I tried to play with Resnet. I tried to overfit over small data (3 different images) and see if I can get almost 0 loss and 1.0 accuracy - and I did.

The problem is that predictions on the training images (i.e. the same 3 images used for training) are not correct..

Training Images

Image labels

[1,0,0], [0,1,0], [0,0,1]

My python code

#loading 3 images and resizing them
imgs = np.array([np.array(Image.open("./Images/train/" + fname)
                          .resize((197, 197), Image.ANTIALIAS)) for fname in
                 os.listdir("./Images/train/")]).reshape(-1,197,197,1)
# creating labels
y = np.array([[1,0,0],[0,1,0],[0,0,1]])
# create resnet model
model = ResNet50(input_shape=(197, 197,1),classes=3,weights=None)

# compile & fit model
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['acc'])

model.fit(imgs,y,epochs=5,shuffle=True)

# predict on training data
print(model.predict(imgs))

The model does overfit the data:

3/3 [==============================] - 22s - loss: 1.3229 - acc: 0.0000e+00
Epoch 2/5
3/3 [==============================] - 0s - loss: 0.1474 - acc: 1.0000
Epoch 3/5
3/3 [==============================] - 0s - loss: 0.0057 - acc: 1.0000
Epoch 4/5
3/3 [==============================] - 0s - loss: 0.0107 - acc: 1.0000
Epoch 5/5
3/3 [==============================] - 0s - loss: 1.3815e-04 - acc: 1.0000

but predictions are:

 [[  1.05677405e-08   9.99999642e-01   3.95520459e-07]
 [  1.11955103e-08   9.99999642e-01   4.14905685e-07]
 [  1.02637095e-07   9.99997497e-01   2.43751242e-06]]

which means that all images got label=[0,1,0]

why? and how can that happen?

Body:
What happens is basically that keras.fit() i.e your

model.fit()

is while having the best fit the precision is lost. As, the precision is lost the models fit gives problems and varied results.The keras.fit only has a good fit not the required precision


问:
how to pass data from recyclerview on item clicked in Xamarin.android
I want to launch a new activity with detailed information upon recyclerview item clicked </p>

```<code>  private void OnItemClick(object sender, AluminiAdapterClickEventArgs e)
        {
            var intent = new Intent(Activity, typeof(MovieDetailPage));
            //Toast.MakeText(Activity, "This is photo number " + , ToastLength.Short).Show();
            intent.PutExtra("MovieDetail", e.ItemId);
            //intent.PutExtra("Title", e.Title);
            //intent.PutExtra("Category", e.Category);
            //intent.PutExtra("Discription", e.Discription);
            //intent.PutExtra("Image", e.Image);
            //intent.PutExtra("Amount", e.Amount);
            //intent.PutExtra("Showing_Time", e.Showing_Time);
            StartActivity(intent);
        }
</code>```

答:
According to your description, if you want to pass some string or int value from activity to another activity, you can just use the following code:

```<code>var intent = new Intent(this, typeof(Activity2));
    intent.PutExtra("MyData", "Data from Activity1");
    StartActivity(intent);
</code>```

If you want to pass custom object to another activity, you need to use JSON.Net package that you can install with Nuget Manager. By using JSON you can serialize your object in first activity and then deserialize in the second activity.

Activity1:

```<code>using Newtonsoft.Json;

void mBtnSignIn_Click(object sender,EventArgs e)
 {
  User user = new User();
  user.Name = "John";
  user.Password = "password";

  Intent intent = new Intent(this,typeof(Activity2));
  intent.PutExtra("User",JsonConvert.SerializeObject(user));
  this.StartActivity(intent);
</code>```

}

Activity2:

```<code>using Newtonsoft.Json;

 private User user;
 protected override void OnCreate(Bundle savedInstanceState)
 {
    base.OnCreate(savedInstanceState);

    SetContentView(Resource.Layout.Activity2);
    user = JsonConvert.DeserializeObject<User>(Intent.GetStringExtra("User"));
 }
</code>```

Body:
I want to launch a new activity with detailed information upon recyclerview item clicked

  private void OnItemClick(object sender, AluminiAdapterClickEventArgs e)
        {
            var intent = new Intent(Activity, typeof(MovieDetailPage));
            //Toast.MakeText(Activity, "This is photo number " + , ToastLength.Short).Show();
            intent.PutExtra("MovieDetail", e.ItemId);
            //intent.PutExtra("Title", e.Title);
            //intent.PutExtra("Category", e.Category);
            //intent.PutExtra("Discription", e.Discription);
            //intent.PutExtra("Image", e.Image);
            //intent.PutExtra("Amount", e.Amount);
            //intent.PutExtra("Showing_Time", e.Showing_Time);
            StartActivity(intent);
        }

Body:
According to your description, if you want to pass some string or int value from activity to another activity, you can just use the following code:

var intent = new Intent(this, typeof(Activity2));
    intent.PutExtra("MyData", "Data from Activity1");
    StartActivity(intent);

If you want to pass custom object to another activity, you need to use JSON.Net package that you can install with Nuget Manager. By using JSON you can serialize your object in first activity and then deserialize in the second activity.

Activity1:

using Newtonsoft.Json;

void mBtnSignIn_Click(object sender,EventArgs e)
 {
  User user = new User();
  user.Name = "John";
  user.Password = "password";

  Intent intent = new Intent(this,typeof(Activity2));
  intent.PutExtra("User",JsonConvert.SerializeObject(user));
  this.StartActivity(intent);

}

Activity2:

using Newtonsoft.Json;

 private User user;
 protected override void OnCreate(Bundle savedInstanceState)
 {
    base.OnCreate(savedInstanceState);

    SetContentView(Resource.Layout.Activity2);
    user = JsonConvert.DeserializeObject<User>(Intent.GetStringExtra("User"));
 }


问:
VBA "On Error Goto" not surpassing the Errors
Solution By Damian works but Does anyone know Why On Error Goto doesn't surpass every type of error in the screenshot, it passes #DIV/0! but not any other error.

I am writing a code to Clean Trim all the cells in the workbook. With luck I am able to do it with the below code.

```<code> On Error GoTo c

    For Each ws In wb.Worksheets

        Set rng = ActiveSheet.UsedRange

        For Each cl In rng

                Debug.Print cl.Address
                cl.Value = WorksheetFunction.Clean(Trim(cl.Value))
                GoTo l
c:

counter = counter + 1

l:
        Next

    Next
</code>```

But the Problem arises when any of the cells contain Error Values like in the Screenshot below.

VBA's On Error Goto is able to surpass the #DIV/0! error and allocate the value to the counter but not for the other errors. It gets stuck on those cells.

答:
This should solve your problems:

```<code> On Error GoTo c
    For Each ws In wb.Worksheets
        Set Rng = ws.UsedRange 'activesheet will always be the sheet you are using clicking the macro button
        For Each cl In Rng
                Debug.Print cl.Address
                If Not IsError(cl) Then cl = WorksheetFunction.Clean(Trim(cl)) 'check first if the value is an error, if it's not then trim
                GoTo l
c:
counter = counter + 1
l:
        Next

    Next
</code>```

Thought using UsedRange will loop through all the cells even if they are blank but once were used. Beware of that.

Body:
Solution By Damian works but Does anyone know Why On Error Goto doesn't surpass every type of error in the screenshot, it passes #DIV/0! but not any other error.

I am writing a code to Clean Trim all the cells in the workbook. With luck I am able to do it with the below code.

 On Error GoTo c

    For Each ws In wb.Worksheets

        Set rng = ActiveSheet.UsedRange

        For Each cl In rng

                Debug.Print cl.Address
                cl.Value = WorksheetFunction.Clean(Trim(cl.Value))
                GoTo l
c:

counter = counter + 1

l:
        Next

    Next

But the Problem arises when any of the cells contain Error Values like in the Screenshot below.

VBA's On Error Goto is able to surpass the #DIV/0! error and allocate the value to the counter but not for the other errors. It gets stuck on those cells.

Body:
This should solve your problems:

 On Error GoTo c
    For Each ws In wb.Worksheets
        Set Rng = ws.UsedRange 'activesheet will always be the sheet you are using clicking the macro button
        For Each cl In Rng
                Debug.Print cl.Address
                If Not IsError(cl) Then cl = WorksheetFunction.Clean(Trim(cl)) 'check first if the value is an error, if it's not then trim
                GoTo l
c:
counter = counter + 1
l:
        Next

    Next

Thought using UsedRange will loop through all the cells even if they are blank but once were used. Beware of that.


问:
Android Instagram login integration
I'm trying to perform social login via Instagram without Graph API and read all the necessary stuff related to it from the Instagram documentation and StackOverflow.

Following are the things I have done in my project till now:

Login developer account of Instagram via my username password.

Manage client > Register new client and add generated Client Id, Secret key and redirect URL in my constant file.

And for the web view, my complete URL is: https://api.instagram.com/oauth/authorize/?client_id=af7efcca661e43459b1e502af7ddb689&redirect_url=https://instagram.com/&response_type=token&scope=basic+public_content

When I enter the username and password in WebView rather than to navigate it on redirect URL it is continuously showing me error on WebView as: {"error_type": "OAuthException", "code": 400, "error_message": "You must include a valid client_id, response_type, and redirect_uri parameters"}

I want to receive access_token but it is showing my error.

Below is my needed code:

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity implements AuthenticationListener {

    private AuthenticationDialog authDialog;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        context = this;
    }

    @Override
    public void onCodeReceived(String token) {
        if (token == null)
            return;
    }

    @OnClick(R.id.buttonLogin)
    public void loginClick() {
        authDialog = new AuthenticationDialog(this, this);
        authDialog.setCancelable(true);
        authDialog.getWindow().setLayout(((getWidth(context) / 100) * 90), LinearLayout.LayoutParams.MATCH_PARENT);
        authDialog.getWindow().setGravity(Gravity.CENTER);
        authDialog.show();
    }

    public static int getWidth(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
}
</code>```

AuthenticationDialog.java

```<code>public class AuthenticationDialog extends Dialog {
    private String TAG = AuthenticationDialog.class.getSimpleName();
    private AuthenticationListener listener;
    private Context context;
    private WebView webView;

    private final String url = Constants.BASE_URL + "oauth/authorize/?client_id=" +
            Constants.INSTAGRAM_CLIENT_ID
            + "&redirect_url="
            + Constants.REDIRECT_URL
            + "&response_type=token"
            + "&scope=basic+public_content";

    public AuthenticationDialog(@NonNull Context context, AuthenticationListener listener) {
        super(context);

        this.context = context;
        this.listener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.auth_dialog);
        initializeWebView();
    }

    private void initializeWebView() {
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
        Log.d(TAG, "url: " + url);
        //webView.loadUrl("http://api.instagram.com/");
        //webView.loadUrl("https://api.instagram.com/oauth/authorize/?client_id=af7efcca661e43459b1e502af7ddb689&redirect_uri=https://instagram.com/&response_type=token&scope=basic+public_content");
        webView.setWebViewClient(new WebViewClient() {

            String access_token;
            boolean authComplete;

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.d(TAG, "onPageStarted called");
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.d(TAG, "onPageFinished called");
                if (url.contains("#access_token=") && !authComplete) {
                    Log.d(TAG, " inside access_token");
                    Uri uri = Uri.parse(url);
                    access_token = uri.getEncodedFragment();
                    //get the whole token after "=" sign
                    access_token = access_token.substring(access_token.lastIndexOf("=") + 1);
                    Log.d(TAG, "token: " + access_token);
                    authComplete = true;
                    listener.onCodeReceived(access_token);
                    dismiss();
                } else if (url.contains("?error")) {
                    Log.d(TAG, "getting error fetching access token");
                    dismiss();
                } else {
                    Log.d(TAG, "outside both" + url.toString());
                }
            }
        });
    }
}
</code>```

and according to logs the code is coming in last else "outside both" Also the WebView is showing the error which I mentioned in point no. 4.

Can anyone please help?

答:
Well, You can simply test it out on Web Browser with the URL to check if the URL is valid or not. And I guess It's not a java code problem but your setting problem in the Manage Clients

Make sure if the client_id is correct and redirect_url is the same in the setting on the instagram developer site.

Title: Android Instagram login integration

Body:
I'm trying to perform social login via Instagram without Graph API and read all the necessary stuff related to it from the Instagram documentation and StackOverflow.

Following are the things I have done in my project till now:

Login developer account of Instagram via my username password.

Manage client > Register new client and add generated Client Id, Secret key and redirect URL in my constant file.

And for the web view, my complete URL is: https://api.instagram.com/oauth/authorize/?client_id=af7efcca661e43459b1e502af7ddb689&redirect_url=https://instagram.com/&response_type=token&scope=basic+public_content

When I enter the username and password in WebView rather than to navigate it on redirect URL it is continuously showing me error on WebView as: {"error_type": "OAuthException", "code": 400, "error_message": "You must include a valid client_id, response_type, and redirect_uri parameters"}

I want to receive access_token but it is showing my error.

Below is my needed code:

MainActivity.java

public class MainActivity extends AppCompatActivity implements AuthenticationListener {

    private AuthenticationDialog authDialog;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        context = this;
    }

    @Override
    public void onCodeReceived(String token) {
        if (token == null)
            return;
    }

    @OnClick(R.id.buttonLogin)
    public void loginClick() {
        authDialog = new AuthenticationDialog(this, this);
        authDialog.setCancelable(true);
        authDialog.getWindow().setLayout(((getWidth(context) / 100) * 90), LinearLayout.LayoutParams.MATCH_PARENT);
        authDialog.getWindow().setGravity(Gravity.CENTER);
        authDialog.show();
    }

    public static int getWidth(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
}

AuthenticationDialog.java

public class AuthenticationDialog extends Dialog {
    private String TAG = AuthenticationDialog.class.getSimpleName();
    private AuthenticationListener listener;
    private Context context;
    private WebView webView;

    private final String url = Constants.BASE_URL + "oauth/authorize/?client_id=" +
            Constants.INSTAGRAM_CLIENT_ID
            + "&redirect_url="
            + Constants.REDIRECT_URL
            + "&response_type=token"
            + "&scope=basic+public_content";

    public AuthenticationDialog(@NonNull Context context, AuthenticationListener listener) {
        super(context);

        this.context = context;
        this.listener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.auth_dialog);
        initializeWebView();
    }

    private void initializeWebView() {
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
        Log.d(TAG, "url: " + url);
        //webView.loadUrl("http://api.instagram.com/");
        //webView.loadUrl("https://api.instagram.com/oauth/authorize/?client_id=af7efcca661e43459b1e502af7ddb689&redirect_uri=https://instagram.com/&response_type=token&scope=basic+public_content");
        webView.setWebViewClient(new WebViewClient() {

            String access_token;
            boolean authComplete;

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.d(TAG, "onPageStarted called");
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.d(TAG, "onPageFinished called");
                if (url.contains("#access_token=") && !authComplete) {
                    Log.d(TAG, " inside access_token");
                    Uri uri = Uri.parse(url);
                    access_token = uri.getEncodedFragment();
                    //get the whole token after "=" sign
                    access_token = access_token.substring(access_token.lastIndexOf("=") + 1);
                    Log.d(TAG, "token: " + access_token);
                    authComplete = true;
                    listener.onCodeReceived(access_token);
                    dismiss();
                } else if (url.contains("?error")) {
                    Log.d(TAG, "getting error fetching access token");
                    dismiss();
                } else {
                    Log.d(TAG, "outside both" + url.toString());
                }
            }
        });
    }
}

and according to logs the code is coming in last else "outside both" Also the WebView is showing the error which I mentioned in point no. 4.

Can anyone please help?


问:
How to precompile assets before running a Rails App on a ECS Fargate environment?
I have a CodePipeline set-up that tracks updates to a private GIT repo. When a change is detected, a CodeBuild task is run to turn the repo into a Docker Image and pushes it to ECR. After that I run a CodeDeploy task to update the ECS cluster by running rake db:migrate and restarting the tasks.

All fine so far. But when I try to access my Rails app, I'm seeing the following error:

ActionView::Template::Error occurred while GET </> was processed by statics#home
Exception
The asset "application.css" is not present in the asset pipeline.

It seems that I need to run rake assets:precompile somewhere. I don't know how to make that work, should I:

Define the precompilation in my Dockerfile?

run the command in my CodeBuild script?

Do something else?

Thanks in advance

答:
In Dockerfile -
RUN bundle exec rake assets:precompile</p>


问:
I can't run Docker ToolBox on Windows 7
I can't start docker toolbox on windows 7.
This are few steps i did.

1) I download Docker Toolbox from official site.

2) Installed it

3)Installed virtualbox.exe from docker directory.

4) When i run QUICKSTART DOCKER TERMINAL i get this after few settings:
Looks like something went wrong in step ´Setting env´... Press any key to continue...

So i can't run it. What shall i d0?
Also i can't start start.sh

I can see docker --version from git,cmd, and created by docker in vb linux.
Also i can run hello-world from linux console from vb.
But how can i start docker?

Basically i don't understand where i need to work with docker from.

From my windows termianl or only from vb linux terminal

答:
run as administrator a cmd and run this command

"C:\Program Files\Git\bin\bash.exe" --login -i "C:\Program Files\Docker Toolbox\start.sh"

Title: I can't run Docker ToolBox on Windows 7


问:
How does CosmosDB distribute throughput when provisioned per database (shared RUs)
I have a problem understading how distribution of provisioned throughput works if I set up Cosmos DB to use shared RUs - setting RUs at database level.

I know when set on container (collection) level that throughput is divided between logical partitions e.g. if collection has provisioned throughput 400 RU/s and 10 logical partitions then throughput for each partition is 400/10 = 40 RU/s.

But what about when throughput is set per database?
Only documentation I found is https://learn.microsoft.com/en-us/azure/cosmos-db/set-throughput#set-throughput-on-a-database
As far as I can tell difference is that physical partitions are not dedicated to single container but can host logical partitions from different containers  - does this mean that throughput is divided between all logical partitions of all collections/containers?

For example: I have database with throughput 1000 RU/s and 2 collections, one with 3 logical partitions and second with 7 logical partitions, so is throughput divided 1000 / (3 + 7) = 100 RU/s for each logical partition?

OR
Is throughput reserved for all collections/partitions in sum? e.g. there is database with 1000 RU/s and one logical partitions use 800RU/s and other use 200RU/s (no matter what collection) then is it ok as long as they in sum dont exceed 1000 RU/s ?

Maybe question is short - is shared throughput distributed evenly between logical partitions (same as when set on collection level) or is not (somehow different)?

答:
Thanks for your feedback. If you are configuring the throughput at database level. You cannot guarantee the throughput for each containers in it, unless you configure the throughput for containers as well.

All containers created inside a database with provisioned throughput must be created with a partition key. At any given point of time, the throughput allocated to a container within a database is distributed across all the logical partitions of that container. When you have containers that share provisioned throughput configured on a database, you can't selectively apply the throughput to a specific container or a logical partition.

You can follow this URL for understading the effect of setting throughput at database and containers level.
Set throughput on a database and a container

Hope it helps.


问:
Android Management API and MDM
I was going through the new Android Management API.

Now, Google has their own app called Android Device Policy which acts as an MDM app but MDM apps don't require a factory reset but why do we have to factory reset the device when enrolling with AFW using Android Management API.

Can't the Android Device Policy be manually installed and set as the device administrator?

答:
May 2019 update

Now Android Management Api and Android Device Policy (the Android app that acts as DPC) supports both Work Profile and Device Owner modes.
There are also more enroll methods, one of the most easy is using QRs.

To manage the devices, create/assign policies, etc. you can interact with the API just with Google API Explorer but it's better to use an EMM console of sort.
I'm working on a very simple interface, I think I'll publish it on Github when ready.

I've tested only with a Samsung A5 2017 with Android 8.0.0 and an Android 9.0 device...not an extensive tests suite!

Title: Android Management API and MDM


问:
Pass multiple lines of stdin input to interactive Java command line program, non-interactively
I have a command-line java program that takes a password and it's verification from stdin. Unfortunately, modifying the program isn't an option as it is proprietary.

I'm unable to pass the arguments from the unix command line using < since there are two prompts in the program, both asking for the same password. There are stdout statements asking for "Password" and "Password (validation):" on the command prompt.

How can I pass the password non-interactively to this program so that it can be executed automatically using a cron job / RC script?

Thanks!

答:
Chances are that the password is not read from stdin at all, but from /dev/tty. In that case you're out of luck.

Can you run the program by feeding all the input including the passwords through stdin? If not, then you're out of luck.

If this works, however, you can do something like

```<code>(echo user; echo passwd1; echo passwd1; cat) | java -jar yourCommandlineprogram.jar
</code>```

Body:
Chances are that the password is not read from stdin at all, but from /dev/tty. In that case you're out of luck.

Can you run the program by feeding all the input including the passwords through stdin? If not, then you're out of luck.

If this works, however, you can do something like

(echo user; echo passwd1; echo passwd1; cat) | java -jar yourCommandlineprogram.jar


问:
UserDefaults not working on didload in my project
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

```<code>class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}
</code>```

When the  user clicks login Button, the code is as below

```<code>ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}
</code>```

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

答:
I believe you have a problem with the call to performSegue:. You cannot call this method on viewDidLoad because the viewcontroller is not yet fully setup. Try moving your viewDidLoad to viewDidAppear

Move viewDidLoad code to viewDidAppear

```<code>override func viewDidAppear(animated: Bool){
    super.viewDidAppear(animated)
    if User.isLoggedIn{
        performSegue("someIdentifier")
    }else{
       //show some alerts.
    }

}

</code>```

Also, use a computed var for your isLoggedIn.
taken from Marco:

```<code>
  static var isLoggedIn: Bool {
        get {
            return UserDefaults.standard.bool(forKey: "islogged")
        }
        set(aIsLoggedIn) {
            UserDefaults.standard.set(aIsLoggedIn, forKey: "islogged")
        }
    }
</code>```

Perform Segue on ViewDidLoad

Body:
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}

When the  user clicks login Button, the code is as below

ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

Body:
I believe you have a problem with the call to performSegue:. You cannot call this method on viewDidLoad because the viewcontroller is not yet fully setup. Try moving your viewDidLoad to viewDidAppear

Move viewDidLoad code to viewDidAppear

override func viewDidAppear(animated: Bool){
    super.viewDidAppear(animated)
    if User.isLoggedIn{
        performSegue("someIdentifier")
    }else{
       //show some alerts.
    }

}

Also, use a computed var for your isLoggedIn.
taken from Marco:

  static var isLoggedIn: Bool {
        get {
            return UserDefaults.standard.bool(forKey: "islogged")
        }
        set(aIsLoggedIn) {
            UserDefaults.standard.set(aIsLoggedIn, forKey: "islogged")
        }
    }

Perform Segue on ViewDidLoad


问:
understanding equality from istream_iterator
Can someone please explain why this istream_iterator code.

```<code>// code extract from SGI STL istream_iterator class
bool _M_equal(const istream_iterator& __x) const {
   return (_M_ok == __x.M_ok) && (!_M_ok || _M_stream == __x._M_stream);
}
</code>```

works and is not just written as

```<code>bool _M_equal(const istream_iterator& __x) const {
   return (_M_ok == __x.M_ok) && (_M_stream == __x._M_stream);
}
</code>```

I don't understanding the reason for including !_M_ok. Thanks in advance.

答: _M_stream == __x._M_stream has undefined behaviour if either _M_ok or __x._M_ok is false.

Body:
Can someone please explain why this istream_iterator code.

// code extract from SGI STL istream_iterator class
bool _M_equal(const istream_iterator& __x) const {
   return (_M_ok == __x.M_ok) && (!_M_ok || _M_stream == __x._M_stream);
}

works and is not just written as

bool _M_equal(const istream_iterator& __x) const {
   return (_M_ok == __x.M_ok) && (_M_stream == __x._M_stream);
}

I don't understanding the reason for including !_M_ok. Thanks in advance.


问:
Parallel processing using DataFrames in Julia
I am referring to the example in the documentation for processing Parallel loops and trying to adapt it for my use case. In each independent iteration in my case, I  get a DataFrame as a result which I need to finally combine across all iterations using vcat(). This is a simplified version of my attempt so far:

```<code>using DataFrames, Distributed

function test()
    if length(workers()) < length(Sys.cpu_info())
        addprocs(length(Sys.cpu_info()); exeflags="--project=" * Base.active_project())
    end

    nheads = @distributed (vcat) for i = 1:20
        DataFrame(a=[Int(rand(Bool))])
    end
end
</code>```

But on running test(), I get the error:

ERROR: On worker 2: UndefVarError: DataFrame not defined

What do I need to do to correct this?

答:
Your using DataFrames ... statement on the first line only applies to the main "thread". So your worker threads didn't import the required libraries.

To fix this, you should add the keyword @everywhere on the first line. That would ask all the processes to import those libraries.

Edit

Just noticed that you did addprocs in the function. Then my suggestion wouldn't work. Here's a working version:

```<code>using Distributed

addprocs(length(Sys.cpu_info()))

@everywhere using DataFrames

function test()
    nheads = @distributed (vcat) for i = 1:20
        DataFrame(a=[Int(rand(Bool))])
    end
end

test()
</code>```

Body:
I am referring to the example in the documentation for processing Parallel loops and trying to adapt it for my use case. In each independent iteration in my case, I  get a DataFrame as a result which I need to finally combine across all iterations using vcat(). This is a simplified version of my attempt so far:

using DataFrames, Distributed

function test()
    if length(workers()) < length(Sys.cpu_info())
        addprocs(length(Sys.cpu_info()); exeflags="--project=" * Base.active_project())
    end

    nheads = @distributed (vcat) for i = 1:20
        DataFrame(a=[Int(rand(Bool))])
    end
end

But on running test(), I get the error:

ERROR: On worker 2: UndefVarError: DataFrame not defined

What do I need to do to correct this?

Body:
Your using DataFrames ... statement on the first line only applies to the main "thread". So your worker threads didn't import the required libraries.

To fix this, you should add the keyword @everywhere on the first line. That would ask all the processes to import those libraries.

Edit

Just noticed that you did addprocs in the function. Then my suggestion wouldn't work. Here's a working version:

using Distributed

addprocs(length(Sys.cpu_info()))

@everywhere using DataFrames

function test()
    nheads = @distributed (vcat) for i = 1:20
        DataFrame(a=[Int(rand(Bool))])
    end
end

test()


问:
Android: integer from xml resource
How do I have to modify my XML resources, or what XML file do I have to create, to access integer values in the same way you access string values with R.string.some_string_resource ?

For example, in the code I want to say:

```<code>ProgressDialog progressBar = new ProgressDialog(getContext());
progressBar.setMax(getInteger(R.integer.maximum));
</code>```

Is it possible?

答:
You must add the integers.xml file to your project

and then

and in integers.xml add this

```<code><integer name="maximum">5</integer>
</code>```

Title: Android: integer from xml resource

Body:
How do I have to modify my XML resources, or what XML file do I have to create, to access integer values in the same way you access string values with R.string.some_string_resource ?

For example, in the code I want to say:

ProgressDialog progressBar = new ProgressDialog(getContext());
progressBar.setMax(getInteger(R.integer.maximum));

Is it possible?

Body:
You must add the integers.xml file to your project

and then

and in integers.xml add this

<integer name="maximum">5</integer>


问:
How to set background image only for a part of the textView
I have a multiline textview and i want to set a background image only at the last three characters of the textview -> from tv.length() - 3 to tv.lenght()</p>

答:
I think this will work:</p>

```<code>Spannable spannable = new SpannableString(text);

spannable.setSpan(new ForegroundColorSpan(Color.WHITE), text.length(), text.length()-3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

myTextView.setText(spannable, TextView.BufferType.SPANNABLE);
</code>```

Body:
I think this will work:

Spannable spannable = new SpannableString(text);

spannable.setSpan(new ForegroundColorSpan(Color.WHITE), text.length(), text.length()-3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

myTextView.setText(spannable, TextView.BufferType.SPANNABLE);


问:
Cannot convert 'System.Object[]' to the type 'System.String'
I'm trying to establish a connection to a remote server that is not on Domain environment.
When running the Set-Item alone on PowerShell console without the script it works for some reason on the script it doesn't.

```<code>$passwd = convertto-securestring -String <Password> -AsPlainText -Force
$cred = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList "developer", $passwd
$server = Read-Host -Prompt 'Input your server IP'

Set-Item wsman:\localhost\client\TrustedHosts -Value $server -Force

$session = new-pssession -computername $server -credential $cred
</code>```

When I run the above code, I receive the message

Set-Item : Cannot convert 'System.Object[]' to the type
'System.String' required by the parameter. Specified method is not supported.

答:
When you are passing the input here, it should be a string value and a single object, if there is a comma or something, then the $server no more remains as string.
To do a forceful conversion, you can convert the $server explicitly to String type by type casting:

```<code>[String]$server = Read-Host -Prompt 'Input your server IP'
</code>```

Further,

I would like you to hardcode the server name in the Set-Item and see if you are getting the error. You will not get it mostly.

```<code>Set-Item wsman:\localhost\client\TrustedHosts -Value 'YourServerHostname' -Force
</code>```

So, validate while taking the input that what kind of input you are getting.

Body:
I'm trying to establish a connection to a remote server that is not on Domain environment.
When running the Set-Item alone on PowerShell console without the script it works for some reason on the script it doesn't.

$passwd = convertto-securestring -String <Password> -AsPlainText -Force
$cred = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList "developer", $passwd
$server = Read-Host -Prompt 'Input your server IP'

Set-Item wsman:\localhost\client\TrustedHosts -Value $server -Force

$session = new-pssession -computername $server -credential $cred

When I run the above code, I receive the message

Set-Item : Cannot convert 'System.Object[]' to the type
'System.String' required by the parameter. Specified method is not supported.

Body:
When you are passing the input here, it should be a string value and a single object, if there is a comma or something, then the $server no more remains as string.
To do a forceful conversion, you can convert the $server explicitly to String type by type casting:

[String]$server = Read-Host -Prompt 'Input your server IP'

Further,

I would like you to hardcode the server name in the Set-Item and see if you are getting the error. You will not get it mostly.

Set-Item wsman:\localhost\client\TrustedHosts -Value 'YourServerHostname' -Force

So, validate while taking the input that what kind of input you are getting.