问:
Python 3.4: py2exe not compiling program with tkinter
I was trying to compile my program using py2exe with the setup.py and all but whenever I try the console gives me this:

```<code>Traceback (most recent call last):
  File "setup.py", line 10, in <module>
zipfile = None)
  File "C:\Python34\lib\distutils\core.py", line 149, in setup
dist.run_commands()
  File "C:\Python34\lib\distutils\dist.py", line 955, in run_commands
self.run_command(cmd)
  File "C:\Python34\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
  File "C:\Python34\lib\site-packages\py2exe\distutils_buildexe.py", line 188, in run
self._run()
  File "C:\Python34\lib\site-packages\py2exe\distutils_buildexe.py", line 267, in _run
builder.analyze()
  File "C:\Python34\lib\site-packages\py2exe\runtime.py", line 164, in analyze
mf.import_hook(modname)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 120, in import_hook
    module = self._gcd_import(name)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 274, in _gcd_import
    return self._find_and_load(name)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 337, in
_find_and_load
    raise ImportError(name)
ImportError: Tkinter
</code>```

I run this via the console using python.exe setup.py py2exe

The setup.py looks something like so:

from distutils.core import setup
import py2exe

```<code>setup(window=[{'script': 'filename.py'}], \
            options={"py2exe": {"includes": ["decimal", "Tkinter", \
            "tkFileDialog", "csv", "xml.dom.minidom", "os"], \
            'bundle_files': 3, 'compressed': False}}, \
            zipfile = None)

excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon",
             "pywin.dialogs", "pywin.dialogs.list",
             "Tkconstants","Tkinter","tcl", "_imagingtk", "PIL._imagingtk",
             "ImageTk", "PIL.ImageTk", "FixTk"
               ]
</code>```

Please help, I do not know what I am doing.

Thank you

答: You are compiling with python 3. In python 3, the package is tkinter, not Tkinter

Body:
I was trying to compile my program using py2exe with the setup.py and all but whenever I try the console gives me this:

Traceback (most recent call last):
  File "setup.py", line 10, in <module>
zipfile = None)
  File "C:\Python34\lib\distutils\core.py", line 149, in setup
dist.run_commands()
  File "C:\Python34\lib\distutils\dist.py", line 955, in run_commands
self.run_command(cmd)
  File "C:\Python34\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
  File "C:\Python34\lib\site-packages\py2exe\distutils_buildexe.py", line 188, in run
self._run()
  File "C:\Python34\lib\site-packages\py2exe\distutils_buildexe.py", line 267, in _run
builder.analyze()
  File "C:\Python34\lib\site-packages\py2exe\runtime.py", line 164, in analyze
mf.import_hook(modname)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 120, in import_hook
    module = self._gcd_import(name)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 274, in _gcd_import
    return self._find_and_load(name)
  File "C:\Python34\lib\site-packages\py2exe\mf3.py", line 337, in
_find_and_load
    raise ImportError(name)
ImportError: Tkinter

I run this via the console using python.exe setup.py py2exe

The setup.py looks something like so:

from distutils.core import setup
import py2exe

setup(window=[{'script': 'filename.py'}], \
            options={"py2exe": {"includes": ["decimal", "Tkinter", \
            "tkFileDialog", "csv", "xml.dom.minidom", "os"], \
            'bundle_files': 3, 'compressed': False}}, \
            zipfile = None)

excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon",
             "pywin.dialogs", "pywin.dialogs.list",
             "Tkconstants","Tkinter","tcl", "_imagingtk", "PIL._imagingtk",
             "ImageTk", "PIL.ImageTk", "FixTk"
               ]

Please help, I do not know what I am doing.

Thank you


来源: stackexchange

问:
window load inside a document ready?
Sorry if this has been answered before but all searches talk about the differences, not about using the two together, if possible.

Simply, can $(window).load.(function() {}) be used INSIDE of $(document).ready.(function() {}) ?

I have some things that should be done after the DOM is loaded but then I want to reveal certain elements only after the images have finished loading.  The only thing that works in Explorer 8, is putting the $(window).load functions inside of the $(document).ready with everything else.

Is this an acceptable practice?

I just want to use the most acceptable method to reveal a DIV that contains small images, like a toolbar, after it's fully constructed.  (visibility hidden versus display none, for example).  The HTML for this DIV is written by the code inside the $(document).ready and then appended to the body using $('body').append() before using the $(window).load.

I'm having lots of problems with Explorer 8.

答:
WARNING:
The answers in this question are quite outdated.

As @ViRuSTriNiTy mentioned in comments that this code is no longer valid in jQuery 3 and it was mentioned as an issue on GitHub.

So this method is not advised anymore.

One way to do it is to use the following code

```<code>$(window).on("load", function(){
   $.ready.then(function(){
      // Both ready and loaded
   });
})
</code>```

However, this code won't work if you load images in ready and want to call some code after it is fully loaded.

ContentLicense: CC BY-SA 3.0

Title: window load inside a document ready?

Body:
WARNING:
The answers in this question are quite outdated.

As @ViRuSTriNiTy mentioned in comments that this code is no longer valid in jQuery 3 and it was mentioned as an issue on GitHub.

So this method is not advised anymore.

One way to do it is to use the following code

$(window).on("load", function(){
   $.ready.then(function(){
      // Both ready and loaded
   });
})

However, this code won't work if you load images in ready and want to call some code after it is fully loaded.


问:
Allowing user to pinch zoom in/out of a webview
I have a WebView into which I'm loading a local HTML page with some embedded images.  I want to allow the user to zoom in on the text and image in a similar fashion as they would with the web browser.

Any ideas how to enable this?

Thanks

答:
For completeness. You must enable multitouch, scalesPagesToFit to get it to work (there are some conditions if its within certain other views).

But then to prevent it scaling your webpage (especially if using local files). You will need to add the following snippet to your HTML

For more info so: http://iphoneincubator.com/blog/windows-views/right-scale-for-a-uiwebview

OwnerDisplayName: Mark

ContentLicense: CC BY-SA 2.5


问:
How to deploy on all GCP instances one-by-one with Ansible?
I'm looking for a solution to deploy my code on all GCP instances of an instance group with ansible. I would list all instances of an instance group and deploy on them one by one to avoid service interruptions.
Any idea ?

Thanks
Thomas

答:
I found the solution. You must add the "serial" key :

```<code>serial: <number>|"<number>%"
</code>```

It sets how many hosts at a time to run at a time. The default is to run tasks on all of a play’s machines at once.

Body:
I found the solution. You must add the "serial" key :

serial: <number>|"<number>%"

It sets how many hosts at a time to run at a time. The default is to run tasks on all of a play’s machines at once.


问:
Get Parameter list of a closure dynamically in Groovy
I have a Closure defined in a groovy file  that load with the shell.evaluate() method.
I need to call this closure in by calling program using the shell."$closurename".call(arguments) call.
However to formulate the closure parameters ( argument above) I'd need to now what are the arguments and arguments names that the closure $Closurename accepts. Is there a way of dynamically knowing this in Groovy? I checked in the metaClass.method property but this does not work in my example below.

Below is the example code.

```<code>        def arguments;
        shell.evaluate(new File("/tmp/myGroovyClosureFile.groovy"))
        testBlock = "myClosureName"
        //Code here to find the parameters for myClosureName and create
        //the arguments variable
        shell."$testBlock".call(arguments)
</code>```

答:
Is there a way of dynamically knowing this in Groovy?

You can't really do it dynamically at runtime.

Body:
I have a Closure defined in a groovy file  that load with the shell.evaluate() method.
I need to call this closure in by calling program using the shell."$closurename".call(arguments) call.
However to formulate the closure parameters ( argument above) I'd need to now what are the arguments and arguments names that the closure $Closurename accepts. Is there a way of dynamically knowing this in Groovy? I checked in the metaClass.method property but this does not work in my example below.

Below is the example code.

        def arguments;
        shell.evaluate(new File("/tmp/myGroovyClosureFile.groovy"))
        testBlock = "myClosureName"
        //Code here to find the parameters for myClosureName and create
        //the arguments variable
        shell."$testBlock".call(arguments)


问:
"CAUTION: provisional headers are shown" in Chrome debugger
I noticed a strange caution message when looking at downloaded resources using Google chrome inspector (F12):

Caution provisional headers are shown

I found something possibly relevant, Network Panel: add caution about provisional request headers, but I could not fully understand it. Related questions can be found Chrome block requests as well as XMLHttpRequest cannot load. Unloaded resources show caution: Provisional headers are shown.

Similar to the first question, my resource was blocked, but later automatically loaded the same resource. Unlike the second question, I don't want to fix anything; I want to know what this message means and why I received it.

答:
Use this code fist of your code:

```<code>header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
</code>```

This works for me.

ContentLicense: CC BY-SA 4.0

Body:
Use this code fist of your code:

header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

This works for me.


问:
AttributeError: 'bool' object has no attribute 'read' when calling requests.post
I'm trying to post a request that with curl looks like this:

```<code>curl -X POST \
    --header "Authorization: Bearer 48378438…" \
    --header "X-Backtory-Storage-Id: 125653265" \
    --form fileItems[0].fileToUpload=@"/path/to/file1.txt"  \
    --form fileItems[0].path="/path1/path2/"    \
    --form fileItems[0].replacing=true  \
    http://storage.backtory.com/files
</code>```

And my code is something like this:

```<code>upload_headers = {'Authorization':'Bearer' + ' ' + access_token, 'X-Backtory-Storage-Id':'48378438**********'}
upload_data = {'fileItems[0].fileToUpload': open('file.txt', 'rb'), 'fileItems[0].path': r'/path1/', 'fileItems[0].replacing': True}
upload_response = requests.post("http://storage.backtory.com/files", files=upload_data, headers=upload_headers)
print(upload_r)
</code>```

But after running this code I get this error:

```<code>Traceback (most recent call last):
  File "backtory-test.py", line 27, in <module>
    upload_r = requests.post("http://storage.backtory.com/files", files=upload_data, headers=upload_headers)
  File "C:\Program Files\Python36\lib\site-packages\requests\api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\requests\api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\requests\sessions.py", line 494, in request
    prep = self.prepare_request(req)
  File "C:\Program Files\Python36\lib\site-packages\requests\sessions.py", line 437, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\Program Files\Python36\lib\site-packages\requests\models.py", line 308, in prepare
    self.prepare_body(data, files, json)
  File "C:\Program Files\Python36\lib\site-packages\requests\models.py", line 496, in prepare_body
    (body, content_type) = self._encode_files(files, data)
  File "C:\Program Files\Python36\lib\site-packages\requests\models.py", line 159, in _encode_files
    fdata = fp.read()
AttributeError: 'bool' object has no attribute 'read'
</code>```

Which section of my code is buggy?

答:
Every value in the files dictionary must be a file-descriptor-like object (ie have a read method) or a tuple (see below).

True neither has such method (as the error says) nor is a tuple.

So

```<code>upload_data = {'fileItems[0].fileToUpload': open('file.txt', 'rb'),
               'fileItems[0].path': r'/path1/',
               'fileItems[0].replacing': True}
</code>```

should simply be

```<code>upload_data = {'filename': open('file.txt', 'rb')}
</code>```

Another option is to provide a tuple as a value. This allows you to set some options. You can read more on requests docs.

path and replacing sound like variables that you should post as data and not as part of the files dictionary.

Body:
I'm trying to post a request that with curl looks like this:

curl -X POST \
    --header "Authorization: Bearer 48378438…" \
    --header "X-Backtory-Storage-Id: 125653265" \
    --form fileItems[0].fileToUpload=@"/path/to/file1.txt"  \
    --form fileItems[0].path="/path1/path2/"    \
    --form fileItems[0].replacing=true  \
    http://storage.backtory.com/files

And my code is something like this:

upload_headers = {'Authorization':'Bearer' + ' ' + access_token, 'X-Backtory-Storage-Id':'48378438**********'}
upload_data = {'fileItems[0].fileToUpload': open('file.txt', 'rb'), 'fileItems[0].path': r'/path1/', 'fileItems[0].replacing': True}
upload_response = requests.post("http://storage.backtory.com/files", files=upload_data, headers=upload_headers)
print(upload_r)

But after running this code I get this error:

Traceback (most recent call last):
  File "backtory-test.py", line 27, in <module>
    upload_r = requests.post("http://storage.backtory.com/files", files=upload_data, headers=upload_headers)
  File "C:\Program Files\Python36\lib\site-packages\requests\api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\requests\api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\requests\sessions.py", line 494, in request
    prep = self.prepare_request(req)
  File "C:\Program Files\Python36\lib\site-packages\requests\sessions.py", line 437, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\Program Files\Python36\lib\site-packages\requests\models.py", line 308, in prepare
    self.prepare_body(data, files, json)
  File "C:\Program Files\Python36\lib\site-packages\requests\models.py", line 496, in prepare_body
    (body, content_type) = self._encode_files(files, data)
  File "C:\Program Files\Python36\lib\site-packages\requests\models.py", line 159, in _encode_files
    fdata = fp.read()
AttributeError: 'bool' object has no attribute 'read'

Which section of my code is buggy?

Body:
Every value in the files dictionary must be a file-descriptor-like object (ie have a read method) or a tuple (see below).

True neither has such method (as the error says) nor is a tuple.

So

upload_data = {'fileItems[0].fileToUpload': open('file.txt', 'rb'),
               'fileItems[0].path': r'/path1/',
               'fileItems[0].replacing': True}

should simply be

upload_data = {'filename': open('file.txt', 'rb')}

Another option is to provide a tuple as a value. This allows you to set some options. You can read more on requests docs.

path and replacing sound like variables that you should post as data and not as part of the files dictionary.


问:
How can I open an editable, sendable e-mail screen with prepopoulated values?
I am trying to create an e-mail with to and from already filled in. To create the e-mail, I'm creating a graph instance of CREmailActivityMaint. Whenever I attempt to assign new objects to the CREmailActivityMaint.CurrentMessage or CREmailActivityMaint.Message objects so that I can set values, the opening page becomes uneditable and Send is hidden:

Also when I enter values, not all of them show. In this,  I entered To, From, Subject, Summary, and Body, but Body and Summary show nothing. Also if I attempt to save, I get an error stating that the Summary, To, and Subject are blank:

答:
```<code>    CREmailActivityMaint graph = CreateInstance<CREmailActivityMaint>();
    graph.Message.Current = graph.Message.Insert();
    graph.Message.Current.MailTo = "other@test.com";
    graph.Message.Current.MailCc = "another@test.com";
    graph.Message.Current.MailBcc = "bcc@test.com";
    graph.Message.Current.Subject = "Subject";
    graph.Message.Current.Body = "Body";
    graph.Message.Cache.IsDirty = false;
    PXRedirectHelper.TryRedirect(graph, PXRedirectHelper.WindowMode.NewWindow);
</code>```


问:
Receive events from a listener object
How can I register to be notified of a listener object's events?

Essentially what I'm trying to achieve can be visualized through this:

this.mouseMoved() = listener.mouseMoved()

```<code>Class Secondary implements MouseMotionListener {

    public Secondary(MouseMotionListener listener) {

        // Here Secondary needs to be registered to the same observer that
        // listener is getting notified from so that the Secondary class's
        // mouseMoved() and mouseDragged() both fire at the same time and
        // with the same MouseEvents as the listener's.
    }

    @Override
    void mouseMoved(MouseEvent e) {

        // This needs to be essentially the same as the events fired
        // in the constructor's parameter object
    }

    @Override
    void mouseDragged(MouseEvent e) {

        // This needs to be essentially the same as the events fired
        // in the constructor's parameter object
    }
}
</code>```

答:
A listener is fired by someone that calls the methods, JComponents accepts mouselisteners as arguments so you must set it:

```<code>JPanel panel = new JPanel();
jFrame.add(panel);
panel.addMouseListener(new Secondary());
</code>```

You can use the delegate pattern if you want to dispatch the events.

```<code>class Secondary implements MouseMotionListener {
MouseMotionListener other;
public Secondary(MouseMotionListener listener) {
    other = listener;
}

@Override
void mouseMoved(MouseEvent e) {
    other.mouseMoved(e);
}

@Override
void mouseDragged(MouseEvent e) {
    other.mouseDragged(e);
}
}
</code>```

Title: Receive events from a listener object

Body:
How can I register to be notified of a listener object's events?

Essentially what I'm trying to achieve can be visualized through this:

this.mouseMoved() = listener.mouseMoved()

Class Secondary implements MouseMotionListener {

    public Secondary(MouseMotionListener listener) {

        // Here Secondary needs to be registered to the same observer that
        // listener is getting notified from so that the Secondary class's
        // mouseMoved() and mouseDragged() both fire at the same time and
        // with the same MouseEvents as the listener's.
    }

    @Override
    void mouseMoved(MouseEvent e) {

        // This needs to be essentially the same as the events fired
        // in the constructor's parameter object
    }

    @Override
    void mouseDragged(MouseEvent e) {

        // This needs to be essentially the same as the events fired
        // in the constructor's parameter object
    }
}

Body:
A listener is fired by someone that calls the methods, JComponents accepts mouselisteners as arguments so you must set it:

JPanel panel = new JPanel();
jFrame.add(panel);
panel.addMouseListener(new Secondary());

You can use the delegate pattern if you want to dispatch the events.

class Secondary implements MouseMotionListener {
MouseMotionListener other;
public Secondary(MouseMotionListener listener) {
    other = listener;
}

@Override
void mouseMoved(MouseEvent e) {
    other.mouseMoved(e);
}

@Override
void mouseDragged(MouseEvent e) {
    other.mouseDragged(e);
}
}


问:
Unable to detect touch inside internet explorer or microsoft edge
I have setup a global hook for WH_GETMESSAGE and WH_CALLWNDPROC. And I am trying to detect touch made on the screen. I am able to do so for everything that's there in the screen except for Microsoft Edge and the client area of Internet Explorer.

By that, I mean I am unable to detect if somebody touches an open edge or the client area of an Internet Explorer Window. But the same works for Google Chrome or other browsers. Any idea why this is happening and what should my approach be, to deal with it?

I have shared a portion of my hook proc code below.

```<code>LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    switch (lpMsg->message)
    {
    case WM_POINTERDOWN:
        UINT32 pointerId = GET_POINTERID_WPARAM(lpMsg->wParam);
        POINTER_INPUT_TYPE pointerType;
        GetPointerType(pointerId, &pointerType);

        if (pointerType == PT_TOUCH)
        {
                   MessageBox(NULL, TEXT("Its a touch"), TEXT("In a DLL"), MB_OK);

        }
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}
</code>```

答:
To hook all applications on the desktop of a 64-bit Windows
  installation, install a 32-bit global hook and a 64-bit global hook,
  each from appropriate processes, and be sure to keep pumping messages
  in the hooking application to avoid blocking normal functioning. If
  you already have a 32-bit global hooking application and it doesn't
  need to run in each application's context, you may not need to create
  a 64-bit version.

The above extract is from somewhere in the below mentioned link:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms644990(v=vs.85).aspx

Body:
I have setup a global hook for WH_GETMESSAGE and WH_CALLWNDPROC. And I am trying to detect touch made on the screen. I am able to do so for everything that's there in the screen except for Microsoft Edge and the client area of Internet Explorer.

By that, I mean I am unable to detect if somebody touches an open edge or the client area of an Internet Explorer Window. But the same works for Google Chrome or other browsers. Any idea why this is happening and what should my approach be, to deal with it?

I have shared a portion of my hook proc code below.

LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    switch (lpMsg->message)
    {
    case WM_POINTERDOWN:
        UINT32 pointerId = GET_POINTERID_WPARAM(lpMsg->wParam);
        POINTER_INPUT_TYPE pointerType;
        GetPointerType(pointerId, &pointerType);

        if (pointerType == PT_TOUCH)
        {
                   MessageBox(NULL, TEXT("Its a touch"), TEXT("In a DLL"), MB_OK);

        }
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}


问:
count multiple strings in R, group by those strings
I have a data.frame like this:

```<code>Points      Assists      Steals
Player A    Player B     Player B
Player B    Player C     Player A
player C    Player C     Player A
</code>```

And I'm trying to get a data.frame output like this:

```<code>           Points     Assists      Steals
Player A    1          0            2
Player B    1          1            1
Player C    1          2            0
</code>```

As you can see, I want it to count the number of times that each player appears in each category. I'm able to do this for one column using table(), but can't figure out how to do it for multiple columns. How would I do this?

答:
Here is the detail of akrun solution for data.table package. It is possible to have a single line, but I expanded it to several understandable steps.

```<code>library(data.table)
DT <- setDT(df1)
DT[,id := 1:.N]
plouf <- melt(DT, id.var = c("id"))
dcast(plouf, value ~variable)
</code>```

gives

```<code>      value Points Assists Steals
1: Player A      1       0      2
2: Player B      1       1      1
3: Player C      1       2      0
</code>```

Body:
I have a data.frame like this:

Points      Assists      Steals
Player A    Player B     Player B
Player B    Player C     Player A
player C    Player C     Player A

And I'm trying to get a data.frame output like this:

           Points     Assists      Steals
Player A    1          0            2
Player B    1          1            1
Player C    1          2            0

As you can see, I want it to count the number of times that each player appears in each category. I'm able to do this for one column using table(), but can't figure out how to do it for multiple columns. How would I do this?

Body:
Here is the detail of akrun solution for data.table package. It is possible to have a single line, but I expanded it to several understandable steps.

library(data.table)
DT <- setDT(df1)
DT[,id := 1:.N]
plouf <- melt(DT, id.var = c("id"))
dcast(plouf, value ~variable)

gives

      value Points Assists Steals
1: Player A      1       0      2
2: Player B      1       1      1
3: Player C      1       2      0


问:
MS Project: Loop through filtered tasks
From a MS-Project I'd like to copy to an excel sheet the task names that meet the criteria of a filter. Let's say filter dumb tasks.
I was trying something but it's not working:

```<code>Dim b As Task

For Each b In ActiveProject.TaskFilters("dumb tasks")
    'code to copy to excel
Next
</code>```

答:
If you are using a custom field Flag3 for the filter, you can loop through the tasks, and check each one if b.Flag3 = True, and then copy this task to Excel.

```<code>Dim b As Task

For Each b In ActiveProject.Tasks
    If b.Flag3 = True Then
        ' here do your copy>>paste to Excel

    End If
Next
</code>```

Title: MS Project: Loop through filtered tasks

Body:
From a MS-Project I'd like to copy to an excel sheet the task names that meet the criteria of a filter. Let's say filter dumb tasks.
I was trying something but it's not working:

Dim b As Task

For Each b In ActiveProject.TaskFilters("dumb tasks")
    'code to copy to excel
Next

Body:
If you are using a custom field Flag3 for the filter, you can loop through the tasks, and check each one if b.Flag3 = True, and then copy this task to Excel.

Dim b As Task

For Each b In ActiveProject.Tasks
    If b.Flag3 = True Then
        ' here do your copy>>paste to Excel

    End If
Next


问:
Singleton, cannot go in the runnable task
I'm trying to run a task automatically (all the 30s).

For that, I built a singleton :

```<code>public class PortalSingleton {
    private static final Logger LOG = LoggerFactory.getLogger(PortalSingleton.class);
    private static final int INITIAL_DELAY = 0;
    private static final int DELAY = 30;

    private static volatile ScheduledExecutorService instance;
    private static HomepageView homeView = new HomepageView();

    private PortalSingleton() {}

    public static final void refreshGridHomePageAutomatically() {
        Runnable task = () -> UI.getCurrent().access(() -> {
            homeView.refreshGrid();
            LOG.info("The grid has been refreshed Automatically");
        });
        getInstance().scheduleWithFixedDelay(task, INITIAL_DELAY, DELAY, TimeUnit.SECONDS);
    }

    public final static ScheduledExecutorService getInstance() {
        if (instance == null) {
            synchronized (ScheduledExecutorService.class) {
                if (instance == null) {
                    instance = Executors.newScheduledThreadPool(1);
                }
            }
        }
        return instance;
    }
}
</code>```

But, I didn't have any issue/error AND I didn't have my log msg and my grid hasn't been refreshed..

The behavior expected is :

my grid refresh

see the log msg

Even if I delete the line homeView.refreshGrid();, I don't have my log msg...

What did I do wrong?

Thanks,

EDIT : I call it by doing : PortalSingleton.refreshGridHomePageAutomatically();

EDIT2, thanks @Holger :

```<code>public class PortalSingleton {
    private static final Logger LOG = LoggerFactory.getLogger(PortalSingleton.class);
    private static final int INITIAL_DELAY = 0;
    private static final int DELAY = 30;

    private static final ScheduledExecutorService instance = Executors.newScheduledThreadPool(1);
    private static HomepageView homeView = new HomepageView();

    private PortalSingleton() {
    }

    public static final void refreshGridHomePageAutomatically() {
        Runnable task = () -> UI.getCurrent().access(() -> {
            homeView.refreshGrid();
            LOG.info("The grid has been refreshed Automatically");
        });
        try {
            getInstance().scheduleWithFixedDelay(task, INITIAL_DELAY, DELAY, TimeUnit.SECONDS);
        } catch (Exception e) {
            LOG.error("error" + e);
        }
    }

    public final static ScheduledExecutorService getInstance() {
        return instance;
    }
}
</code>```

答:
When you schedule an action, you do not get a feedback when an exception occurs. Instead, it will just stop executing it:

ScheduledExecutorService.scheduleWithFixedDelay(…):

…If any execution of the task encounters an exception, subsequent executions are suppressed.

Therefore, you will have to use a try … catch block in the action itself to report it, e.g. in the lambda expression defining your Runnable:

```<code>Runnable task = () -> {
    try { UI.getCurrent().access(…); }
    catch (Exception e) { LOG.error("error" + e); }
};
</code>```

It looks suspicious to me that you are calling UI.getCurrent() from a non-UI thread which I suspect to return null causing a NullPointerException when trying to invoke a method on it.

Body:
I'm trying to run a task automatically (all the 30s).

For that, I built a singleton :

public class PortalSingleton {
    private static final Logger LOG = LoggerFactory.getLogger(PortalSingleton.class);
    private static final int INITIAL_DELAY = 0;
    private static final int DELAY = 30;

    private static volatile ScheduledExecutorService instance;
    private static HomepageView homeView = new HomepageView();

    private PortalSingleton() {}

    public static final void refreshGridHomePageAutomatically() {
        Runnable task = () -> UI.getCurrent().access(() -> {
            homeView.refreshGrid();
            LOG.info("The grid has been refreshed Automatically");
        });
        getInstance().scheduleWithFixedDelay(task, INITIAL_DELAY, DELAY, TimeUnit.SECONDS);
    }

    public final static ScheduledExecutorService getInstance() {
        if (instance == null) {
            synchronized (ScheduledExecutorService.class) {
                if (instance == null) {
                    instance = Executors.newScheduledThreadPool(1);
                }
            }
        }
        return instance;
    }
}

But, I didn't have any issue/error AND I didn't have my log msg and my grid hasn't been refreshed..

The behavior expected is :

my grid refresh

see the log msg

Even if I delete the line homeView.refreshGrid();, I don't have my log msg...

What did I do wrong?

Thanks,

EDIT : I call it by doing : PortalSingleton.refreshGridHomePageAutomatically();

EDIT2, thanks @Holger :

public class PortalSingleton {
    private static final Logger LOG = LoggerFactory.getLogger(PortalSingleton.class);
    private static final int INITIAL_DELAY = 0;
    private static final int DELAY = 30;

    private static final ScheduledExecutorService instance = Executors.newScheduledThreadPool(1);
    private static HomepageView homeView = new HomepageView();

    private PortalSingleton() {
    }

    public static final void refreshGridHomePageAutomatically() {
        Runnable task = () -> UI.getCurrent().access(() -> {
            homeView.refreshGrid();
            LOG.info("The grid has been refreshed Automatically");
        });
        try {
            getInstance().scheduleWithFixedDelay(task, INITIAL_DELAY, DELAY, TimeUnit.SECONDS);
        } catch (Exception e) {
            LOG.error("error" + e);
        }
    }

    public final static ScheduledExecutorService getInstance() {
        return instance;
    }
}

Body:
When you schedule an action, you do not get a feedback when an exception occurs. Instead, it will just stop executing it:

ScheduledExecutorService.scheduleWithFixedDelay(…):

…If any execution of the task encounters an exception, subsequent executions are suppressed.

Therefore, you will have to use a try … catch block in the action itself to report it, e.g. in the lambda expression defining your Runnable:

Runnable task = () -> {
    try { UI.getCurrent().access(…); }
    catch (Exception e) { LOG.error("error" + e); }
};

It looks suspicious to me that you are calling UI.getCurrent() from a non-UI thread which I suspect to return null causing a NullPointerException when trying to invoke a method on it.


问:
jQuery prev next elements
My issue in jQuery code. I have this code jsFiddle.

```<code>$(document).ready(function(){
  $("#clickinput1").click(function (evt) {
     $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
  });
});
</code>```

Before click on button, input is disable and have dark background. I need, when click on button input be enabled(this work) and background change on white color or none. I cannot make this. Please help)

答:
That could be done simply using .css("background-color","white") like :

```<code>$(this).hide().prev("input[disabled]").prop("disabled", false).css("background-color","white").focus();
</code>```

Hope this helps.

$(document).ready(function() {
  $("#clickinput1").click(function(evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).css("background-color", "white").focus();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="customername" class="input" value="" disabled />

<div style="float:right;cursor:pointer;margin:2px 0 0 0px;" id="clickinput1">
  <img src="https://cdn4.iconfinder.com/data/icons/simplicio/128x128/document_edit.png" />button
</div></code>```

Title: jQuery prev next elements

Body:
My issue in jQuery code. I have this code jsFiddle.

$(document).ready(function(){
  $("#clickinput1").click(function (evt) {
     $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
  });
});

Before click on button, input is disable and have dark background. I need, when click on button input be enabled(this work) and background change on white color or none. I cannot make this. Please help)

Body:
That could be done simply using .css("background-color","white") like :

$(this).hide().prev("input[disabled]").prop("disabled", false).css("background-color","white").focus();

Hope this helps.

$(document).ready(function() {
  $("#clickinput1").click(function(evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).css("background-color", "white").focus();
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="customername" class="input" value="" disabled />

<div style="float:right;cursor:pointer;margin:2px 0 0 0px;" id="clickinput1">
  <img src="https://cdn4.iconfinder.com/data/icons/simplicio/128x128/document_edit.png" />button
</div>


问:
How to open the "Find Font" window in InDesign with Applescript
As the title says, I have a script running that checks for missing fonts in an InDesign document. I want it to harass the person with the "Find Font" window until the issue is resolved or they click the "Ignore" button, but I can't for the life of me figure out how to trigger the "Find Font" window to come up.</p>

答:
menu actions is the way to go here...</p>

```<code>tell application "Adobe InDesign CC 2015" to invoke item 1 of (menu actions whose name is "Find Font...")
</code>```

Body:
menu actions is the way to go here...

tell application "Adobe InDesign CC 2015" to invoke item 1 of (menu actions whose name is "Find Font...")


问:
Composite facet for hibernate search
I have two entities: Action and User with many-to-one relationship.

I search for actions and I'd like to have a user full name facet, but instead of a full_name column in the database, I have first_name and last_name.

Is there any way to create a combined facet in hibernate search that would use firstName and lastName together? Or is there a way to create a combined field fullName that will exist in the search index (with a facet) but not in the database?

The mapping is the following:

```<code>@Entity
public class Action {

    ...

    @IndexEmbedded
    private User user;

}

@Entity
public class User {

    ...

    @Facet
    @Field(analyze = Analyze.NO)
    private String firstName;

    @Facet
    @Field(analyze = Analyze.NO)
    private String lastName;

}
</code>```

答:
You can use @Facet and @Field on a method of your User object.

So you can define something like:

```<code>@Facet
@Field
public String getFullName() {
   return new StringJoiner(" ").add(firstName).add(lastName).toString();
}
</code>```

Title: Composite facet for hibernate search

Body:
I have two entities: Action and User with many-to-one relationship.

I search for actions and I'd like to have a user full name facet, but instead of a full_name column in the database, I have first_name and last_name.

Is there any way to create a combined facet in hibernate search that would use firstName and lastName together? Or is there a way to create a combined field fullName that will exist in the search index (with a facet) but not in the database?

The mapping is the following:

@Entity
public class Action {

    ...

    @IndexEmbedded
    private User user;

}

@Entity
public class User {

    ...

    @Facet
    @Field(analyze = Analyze.NO)
    private String firstName;

    @Facet
    @Field(analyze = Analyze.NO)
    private String lastName;

}

Body:
You can use @Facet and @Field on a method of your User object.

So you can define something like:

@Facet
@Field
public String getFullName() {
   return new StringJoiner(" ").add(firstName).add(lastName).toString();
}


问:
Uploading multiple files in .NET through FTP
I am thinking of using following code, but I want to transfer hundreds of files and it does not look viable to connect and then disconnect on every file transfer.

```<code>request = (FtpWebRequest) FtpWebRequest.Create(FtpAddress + file);

request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(User, Pass);

request.UsePassive = IsPassive;
request.UseBinary = true;
request.KeepAlive = false;

FileStream fs = File.OpenRead("");
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();

Stream ftpStream = request.GetRequestStream();
ftpStream.Write(buffer, 0, buffer.Length);

ftpStream.Close();
</code>```

What options do I have for uploading all of these files using a single connection?

答:
I have not verified this to be true, but in my quick 30 second search, if you set

```<code>request.KeepAlive = true;
</code>```

on every request you create except the last one, apparently only the first FTPWebRequest makes a full login connection.

Then when you create the last FTPWebRequest, set

```<code>request.KeepAlive = false;
</code>```

and it will close the connection when done.  You can verify this if you have access to the FTP server's logs.

Body:
I am thinking of using following code, but I want to transfer hundreds of files and it does not look viable to connect and then disconnect on every file transfer.

request = (FtpWebRequest) FtpWebRequest.Create(FtpAddress + file);

request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(User, Pass);

request.UsePassive = IsPassive;
request.UseBinary = true;
request.KeepAlive = false;

FileStream fs = File.OpenRead("");
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();

Stream ftpStream = request.GetRequestStream();
ftpStream.Write(buffer, 0, buffer.Length);

ftpStream.Close();

What options do I have for uploading all of these files using a single connection?

Body:
I have not verified this to be true, but in my quick 30 second search, if you set

request.KeepAlive = true;

on every request you create except the last one, apparently only the first FTPWebRequest makes a full login connection.

Then when you create the last FTPWebRequest, set

request.KeepAlive = false;

and it will close the connection when done.  You can verify this if you have access to the FTP server's logs.


问:
Abstract class logic problems
I am trying to make one program and here is my problem:

I have interface 'Engine'.

EngineFactory.createEngine(request)

In the factory I have:

```<code>if(request instanceof TypeA){ return new TypeAAA(request);}
if(request instanceof TypeB){ return new TypeBBB(request);}
</code>```

Sadly in the constructors when I try to do:

```<code>(TypeA) requestArg
</code>```

It is saying - undefined constructor. Can I do that without the obvious casting of (TypeAAA)TypeA requestArg)?

答:
I assume you want to cast it to TypeA and not TypeAAA if it's instanceof TypeA?

Anyway, yes, you still have to cast it yourself even though you checked if it was an instanceof the class just prior. In Kotlin the compiler would be smart enough to figure it out but with Java you still have to do the cast.

Title: Abstract class logic problems

Body:
I am trying to make one program and here is my problem:

I have interface 'Engine'.

EngineFactory.createEngine(request)

In the factory I have:

if(request instanceof TypeA){ return new TypeAAA(request);}
if(request instanceof TypeB){ return new TypeBBB(request);}

Sadly in the constructors when I try to do:

(TypeA) requestArg

It is saying - undefined constructor. Can I do that without the obvious casting of (TypeAAA)TypeA requestArg)?


问:
Assign custom taxonomy to post with REST API
I'm using the built-in WP REST API to create posts (custom post type). I've got this part working, below is some example JSON I submit to create a new post.

```<code>{
 "title": "The story of Dr Foo",
 "content": "This is the story content",
 "status":"publish",
 "excerpt":"Dr Foo story"
}
</code>```

Problem is, how do I also pass which taxonomies to assign? I can't seem to find a trace of anyone asking or how to do it?

For context, server 1 is creating the posts and WP exists on server 2.

I have also tried passing a long meta data with the request, to which I can then loop over on the WP server and set the taxonomies accordingly with wp_set_post_terms().

To do that, there is this (almost) rest_insert_{$this->post_type} that fires after a single post is created or updated via the REST API.

The problem with this method is that the meta data is not set until AFTER the action_rest_insert_post_type() function has finished. This means that when I try to retrieve the current posts metadata, it doesn't exist.

```<code>function action_rest_insert_post_type( $post, $request, $true ) {

   $items = get_post_meta( $post->ID); // at this point in time, returns empty array.

   //wp_set_terms()

}
</code>```

I have confirmed that $post->ID is working as expected, it's just that the metadata isn't set fully...

Please advise.

答:
```<code>function action_rest_insert_post( $post, $request, $true ) {
    $params = $request->get_json_params();
    if(array_key_exists("terms", $params)) {
        foreach($params["terms"] as $taxonomy => $terms) {
            wp_set_post_terms($post->ID, $terms, $taxonomy);
        }
    }
}

add_action("rest_insert_post", "action_rest_insert_post", 10, 3);
</code>```

I've used post, but this shouldn't be any different for custom post types, just change the action it hooks into.
This works fine for me when being called with something like this:

```<code>{
    "title": "The story of Dr Foo",
    "content": "This is the story content",
    "status":"publish",
    "excerpt":"Dr Foo story",
    "terms": {
        "mytaxonomy": [ "myterm", "anotherterm" ]
    }
}
</code>```

If you wanted to send that data via POST, you'd need to change way to get the params to

```<code>    $params = $request->get_body_params();
</code>```

and send the data as:

title=testtitle&content=testcotnent&status=publish&excerpt=testexcert&terms[mytaxonomy][]=myterm&terms[mytaxonomy][]=anotherterm

Body:
I'm using the built-in WP REST API to create posts (custom post type). I've got this part working, below is some example JSON I submit to create a new post.

{
 "title": "The story of Dr Foo",
 "content": "This is the story content",
 "status":"publish",
 "excerpt":"Dr Foo story"
}

Problem is, how do I also pass which taxonomies to assign? I can't seem to find a trace of anyone asking or how to do it?

For context, server 1 is creating the posts and WP exists on server 2.

I have also tried passing a long meta data with the request, to which I can then loop over on the WP server and set the taxonomies accordingly with wp_set_post_terms().

To do that, there is this (almost) rest_insert_{$this->post_type} that fires after a single post is created or updated via the REST API.

The problem with this method is that the meta data is not set until AFTER the action_rest_insert_post_type() function has finished. This means that when I try to retrieve the current posts metadata, it doesn't exist.

function action_rest_insert_post_type( $post, $request, $true ) {

   $items = get_post_meta( $post->ID); // at this point in time, returns empty array.

   //wp_set_terms()

}

I have confirmed that $post->ID is working as expected, it's just that the metadata isn't set fully...

Please advise.

Body:
function action_rest_insert_post( $post, $request, $true ) {
    $params = $request->get_json_params();
    if(array_key_exists("terms", $params)) {
        foreach($params["terms"] as $taxonomy => $terms) {
            wp_set_post_terms($post->ID, $terms, $taxonomy);
        }
    }
}

add_action("rest_insert_post", "action_rest_insert_post", 10, 3);

I've used post, but this shouldn't be any different for custom post types, just change the action it hooks into.
This works fine for me when being called with something like this:

{
    "title": "The story of Dr Foo",
    "content": "This is the story content",
    "status":"publish",
    "excerpt":"Dr Foo story",
    "terms": {
        "mytaxonomy": [ "myterm", "anotherterm" ]
    }
}

If you wanted to send that data via POST, you'd need to change way to get the params to

    $params = $request->get_body_params();

and send the data as:

title=testtitle&content=testcotnent&status=publish&excerpt=testexcert&terms[mytaxonomy][]=myterm&terms[mytaxonomy][]=anotherterm


问:
SetOnMouseMoved() not working after SetOnMousePressed()
I have a button when I click it runs a function. I also have a separate SetOnMouseMoved event to get information when I hover over other cells in my grid example. My SetOnMouseMoved event will not work after I have pressed the setOnMouseClicked.</p>

```<code>   Button btn = new Button("Uniform Path");
   GridPane gp = new GridPane();
   gp.add(btn, 0,1)

   btn.setOnMouseClicked(new EventHandler<MouseEvent> (){
        @Override
        public void handle(MouseEvent e) {
             SomeFunction();
        }
    });

    // gp.getChildren() refers to StackPane grid cells in which I
    // hover over and get information from that cell.
    for (Node index : gp.getChildren()) {
        index.setOnMouseMoved(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                System.out.print("Row: " + GridPane.getRowIndex(index));
                System.out.println("Column: " + GridPane.getColumnIndex(index));
            }
        });
    }

   Scene scene = new Scene(gp);
</code>```

答:
From docs.oracle.com:

setOnMouseMoved: Defines a function to be called when mouse cursor moves within this Node but no buttons have been pushed.

setOnMouseDragged: Defines a function to be called when a mouse button is pressed on this Node and then dragged.

You just need to implement setOnMouseDragged the same as setOnMouseMoved.

Body:
I have a button when I click it runs a function. I also have a separate SetOnMouseMoved event to get information when I hover over other cells in my grid example. My SetOnMouseMoved event will not work after I have pressed the setOnMouseClicked.

   Button btn = new Button("Uniform Path");
   GridPane gp = new GridPane();
   gp.add(btn, 0,1)

   btn.setOnMouseClicked(new EventHandler<MouseEvent> (){
        @Override
        public void handle(MouseEvent e) {
             SomeFunction();
        }
    });

    // gp.getChildren() refers to StackPane grid cells in which I
    // hover over and get information from that cell.
    for (Node index : gp.getChildren()) {
        index.setOnMouseMoved(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                System.out.print("Row: " + GridPane.getRowIndex(index));
                System.out.println("Column: " + GridPane.getColumnIndex(index));
            }
        });
    }

   Scene scene = new Scene(gp);


问:
list of attributes available to use in networkx
I am working with networkx and cant find a list of available attributes for edges or nodes anywhere.  I am not interested in what attributes are assigned already, but what I can set/change when i create or edit the node or edge.

Can someone point me to where this is documented?

Thanks!

答:
If you want to query a graph for all the possible attributes that might have been applied across the various nodes (and this, for communally created graphs, or ones that have been edited over time, is more common than you might imagine), then the following does the trick for me:

```<code>set(np.array([list(self.graph.node[n].keys()) for n in self.graph.nodes()]).flatten())
</code>```

This returns all possible attribute names for which there are values attributed to graph-nodes. I've imported numpy as np here in order to use np.flatten for (relative) performance, but I'm sure there are various vanilla python alternatives (e.g. try the following itertools.chain method, if you need to avoid numpy )

```<code>from itertools import chain
set(chain(*[(ubrg.graph.node[n].keys()) for n in ubrg.graph.nodes()]))
</code>```

Body:
If you want to query a graph for all the possible attributes that might have been applied across the various nodes (and this, for communally created graphs, or ones that have been edited over time, is more common than you might imagine), then the following does the trick for me:

set(np.array([list(self.graph.node[n].keys()) for n in self.graph.nodes()]).flatten())

This returns all possible attribute names for which there are values attributed to graph-nodes. I've imported numpy as np here in order to use np.flatten for (relative) performance, but I'm sure there are various vanilla python alternatives (e.g. try the following itertools.chain method, if you need to avoid numpy )

from itertools import chain
set(chain(*[(ubrg.graph.node[n].keys()) for n in ubrg.graph.nodes()]))


问:
Can a MenuStrip control have its LayoutStyle set to StackWithOverflow?
I create a simple form with a MenuStrip. The MenuStrip's LayoutStyle is set to HorizontalStackWithOverflow (the default).

According to the MSDN reference on MenuStrip, its LayoutStyle property is inherited from ToolStrip. One of the possible values for the LayoutStyle is HorizontalStackWithOverflow which is also the default setting. This setting should provide items with its Overflow property set to AsNeeded are moved to an overflow button.

When I run the application and resize the form so the menu won't fit completely, this doesn't happen. I've set my ToolStripMenuItems Overflow property to AsNeeded, but when I resize the form, the menu items on the right just disappear.

Is the documentation wrong and can you only get an overflowbutton on a ToolStrip and not on a MenuStrip? Or is there something else I have to do in order to get things working? Or am I just misreading the documentation?

答:
The ToolStrip classes have plenty of hairs like this.  I think the appropriate selection here is LayoutStyle = Flow to get the menu items wrapped.  This is the way the built-in Windows menus work.

You do however have to take care of the layout problem this causes.  Put a Panel on the form with Dock = Fill so that all controls automatically move down when the menu strip needs more space.


问:
TensorFlow - Difference between tf.VariableScope and tf.variable_scope
Have found two links on TensorFlow website referring to variable scope, one is tf.variable_scope which is the one most commonly used, and the other tf.VaribleScope.

As there's no example for the application of tf.VariableScope, just reading through the document, I couldn't distinguish whether there's a difference between the two. Tried to implement by replacing  tf.variable_scope with tf.VariableScope but got the following error (which indicates there're some differences)

```<code>Traceback (most recent call last):
  File "/home/NER/window_model.py", line 105, in <module>
    model = NaiveNERModel(embeddings)
  File "/home/NER/window_model.py", line 64, in __init__
    pred = self.add_prediction_op(embed)
  File "/home/NER/window_model.py", line 82, in add_prediction_op
    with tf.VariableScope('Layer1', initializer=tf.contrib.layers.xavier_initializer()):
AttributeError: __enter__
</code>```

Snippet of the original workable code

with tf.variable_scope('Layer1', initializer=tf.contrib.layers.xavier_initializer()):
        W = tf.get_variable("W", [self.dim * self.window_size, self.dim * self.window_size])
        b1 = tf.get_variable("b1", [self.dim * self.window_size])
        h = tf.nn.relu(tf.matmul(embed, W) + b1)
```

答:
tf.VariableScope is an actual scope class that holds the name, initializer, regularizer, partitioner, and many other properties that are propagated to the variables defined in that scope. This class is more of a collection of properties and not a context manager, so you can't use it in with statement (that's what the error tells you).

Since the scope has to be first pushed on top of the stack (tensorflow internal class _VariableStore is responsible for this), then popped back from the stack, manual instantiation of tf.VariableScope is tedious and error-prone. That's where the context manager comes in.

tf.variable_scope is a context manager that makes it easier to work with variable scopes. As the documentation describes it:

A context manager for defining ops that creates variables (layers).

This context manager validates that the (optional) values are from the same graph, ensures that graph is the default graph, and pushes a name scope and a variable scope.

The actual work with variables is delegated to the tf.VariableScope object that is created under the hood.

Body:
Have found two links on TensorFlow website referring to variable scope, one is tf.variable_scope which is the one most commonly used, and the other tf.VaribleScope.

As there's no example for the application of tf.VariableScope, just reading through the document, I couldn't distinguish whether there's a difference between the two. Tried to implement by replacing  tf.variable_scope with tf.VariableScope but got the following error (which indicates there're some differences)

Traceback (most recent call last):
  File "/home/NER/window_model.py", line 105, in <module>
    model = NaiveNERModel(embeddings)
  File "/home/NER/window_model.py", line 64, in __init__
    pred = self.add_prediction_op(embed)
  File "/home/NER/window_model.py", line 82, in add_prediction_op
    with tf.VariableScope('Layer1', initializer=tf.contrib.layers.xavier_initializer()):
AttributeError: __enter__

Snippet of the original workable code

with tf.variable_scope('Layer1', initializer=tf.contrib.layers.xavier_initializer()):
        W = tf.get_variable("W", [self.dim * self.window_size, self.dim * self.window_size])
        b1 = tf.get_variable("b1", [self.dim * self.window_size])
        h = tf.nn.relu(tf.matmul(embed, W) + b1)


问:
what is the use of service_cluster and service_node in Envoy RDS REST API?
I am trying to develop RDS (Route Discovery Service) to be used with lyft/envoy. As per docs RDS API URL should follow GET /v1/routes/(string: route_config_name)/(string: service_cluster)/(string: service_node). What I want to know is the usage of service_cluster and service_node.

Currently I havent used those for any specific task, just the GET path is matched and a single route is defined. Which is working just fine. I checked what value envoy sends for those and got service_cluster: lax & service_node: node1, not much of help. Docs says these value can also be set via CLI options.

What is it supposed to be used for? Am I missing something?

答:
My understanding is this: Envoy is designed to be a proxy for a microservice, in a mesh of microservices. So you can have multiple envoys getting routes configuration from RDS. When you design your mesh you can decide how you group these multiple envoys - it is a contract between your mesh and your RDS. RDS has two levels of grouping - by service cluster and service node. So you can decide, for example, to call multiple versions of the same microservice service nodes of a service cluster (the microservice with multiple versions).

So you can assign each envoy instance in the mesh a service cluster and a service node identifier and pass to envoy these parameters in the command line. Then envoy will pass them to RDS to get the routes. The RDS then can return different routes to different service clusters and service nodes, if needed by your mesh design.

If you do not use envoy as part of a mesh, i.e. you run just a single envoy, you can just disregard these parameters in your RDS implementation.


问:
rabbitmq using ldap for authentication and internal for authorization in 2 node cluster not working
Morning,

I clustered two servers and it was working with rabbitmq.config that used just the ldap backend.  I tried to change it so it would use ldap just for authentication and internal for authorization, and I can log into the management console on the first server (rabbitmq01p).  However, if I try to access the 2nd server (rabbitmq02p) management console, it now throws:

Got response code 500 with body

This happens even with a test internal user radmin that I created.
I am not sure what needs to change.

The rabbitmq.config:

```<code>[
  {rabbit, [
    {loopback_users, []},
    {auth_backends, [{rabbit_auth_backend_ldap,
rabbit_auth_backend_internal}, rabbit_auth_backend_internal]},
    {log_levels, [{channel, info}, {connection, info}, {federation, info},
    mirroring, info}]},
    {tcp_listen_options,
         [binary,
         {packet,        raw},
         {reuseaddr,     true},
         {backlog,       128},
         {nodelay,       true},
         {exit_on_close, false}]
    },
    {default_user, <<"radmin">>},
    {default_pass, <<"radmin">>}

  ]},
  {kernel, [

  ]}
,
  {rabbitmq_management, [
    {listener, [
      {port, 15672}
    ]}
  ]}
   %% {listener, [{port,     12345},
   %%             {ip,       "127.0.0.1"},
   %%             {ssl,      true},
   %%             {ssl_opts, [{cacertfile, "/path/to/cacert.pem"},
   %%                         {certfile,   "/path/to/cert.pem"},
   %%                         {keyfile,    "/path/to/key.pem"}]}]},
,
{rabbitmq_auth_backend_ldap, [
    {other_bind, {"CN=LDAP Demo,OU=Generic and Shared
Accounts,OU=Admin,dc=usa,dc=company,dc=com", "password"}},
    {servers, ["ldap-server.company.com"]},
    {user_dn_lookup_attribute, "sAMAccountName"},
    {dn_lookup_base, "ou=User Accounts,ou=USA,DC=company,DC=com" },
    {user_dn_pattern, "${username}@usa.company.com" },
    {use_ssl, false},
    {port, 3268},
    {log,true},
    {group_lookup_base, "ou=Groups,dc=usa,dc=company,dc=com"},
    {tag_queries, [{administrator, {in_group, "CN=Server
Team,OU=Groups,DC=usa,DC=company,DC=com"}},
                   {management,    {constant, true}}]}
   ]
  }
].
</code>```

The error in the log:

=ERROR REPORT==== 13-Nov-2017::09:03:26 ===
Ranch listener rabbit_web_dispatch_sup_15672 had connection process started with cowboy_protocol:start_link/4 at <0.1234.0> exit with reason: {[{reason,{badmatch,undefined}},{mfa,{rabbit_mgmt_wm_whoami,is_authorized,2}},{stacktrace,[{rabbit_auth_backend_ldap,env,1,[{file,"src/rabbit_auth_backend_ldap.erl"},{line,580}]},{rabbit_auth_backend_ldap,log,2,[{file,"src/rabbit_auth_backend_ldap.erl"},{line,721}]},{rabbit_auth_backend_ldap,user_login_authentication,2,[{file,"src/rabbit_auth_backend_ldap.erl"},{line,74}]},{rabbit_access_control,try_authenticate,3,[{file,"src/rabbit_access_control.erl"},{line,88}]},{rabbit_access_control,'-check_user_login/2-fun-0-',4,[{file,"src/rabbit_access_control.erl"},{line,65}]},{lists,foldl,3,[{file,"lists.erl"},{line,1248}]},{rabbit_mgmt_util,is_authorized,6,[{file,"src/rabbit_mgmt_util.erl"},{line,160}]},{cowboy_rest,call,3,[{file,"src/cowboy_rest.erl"},{line,976}]}]},{req,[{socket,#Port<0.25192>},{transport,ranch_tcp},{connection,keepalive},{pid,<0.1234.0>},{method,<<"GET">>},{version,'HTTP/1.1'},{peer,{{10,2,2,144},52823}},{host,<<"esrabbitmq02p.usa.company.com">>},{host_info,undefined},{port,15672},{path,<<"/api/whoami">>},{path_info,undefined},{qs,<<>>},{qs_vals,[]},{bindings,[]},{headers,[{<<"host">>,<<"esrabbitmq02p.usa.company.com:15672">>},{<<"connection">>,<<"keep-alive">>},{<<"user-agent">>,<<"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36">>},{<<"authorization">>,<<"Basic cmFkbWpzOnJhZG1pbg==">>},{<<"content-type">>,<<"application/json">>},{<<"accept">>,<<"/">>},{<<"referer">>,<<"http://esrabbitmq02p.usa.company.com:15672/">>},{<<"accept-encoding">>,<<"gzip, deflate">>},{<<"accept-language">>,<<"en-US,en;q=0.8">>},{<<"cookie">>,<<"_SI_VID_1.681cceba2200012815576dcc=3bafef640f2a946d6f48e512; _vwo_uuid_v2=5707BE963C1A8F85D47ABE721862DCD2|e694e7c388bfb2dd860621dc71c082fc; _ceg.s=ow9umn; _ceg.u=ow9umn; RDTC=1; __utmz=234506268.1505479911.21.2.utmcsr=favorites.usa.company.com|utmccn=(referral)|utmcmd=referral|utmcct=/; _SI_VID_3.681cceba2200012815576dcc=3bafef640f2a946d6f48e512; LPVID=lmMWNkODgyOWJiMDYzN2Jk; rxVisitor=15053163485147G3CS2HA9NUHJFVP185Q0ASL8J4DDIV2; amlbcookie=03; iPlanetDirectoryPro=AQIC5wM2LY4Sfcyx28ueXpdDc1glrOUlOpBpriQ5JrEN_3Y.AAJTSQACMDIAAlNLABMtNjg0NTczODcxNTgzMTczMjU1AAJTMQACMDM.; __utma=234506268.404039322.1499344780.1509745463.1510321495.40; __utmc=234506268; _ga=GA1.2.404039322.1499344780; m=2258:cmFkbWluOnJhZG1pbg%253D%253D">>}]},{p_headers,[{<<"connection">>,[<<"keep-alive">>]}]},{cookies,undefined},{meta,[]},{body_state,waiting},{buffer,<<>>},{multipart,undefined},{resp_compress,true},{resp_state,waiting},{resp_headers,[{<<"vary">>,<<"origin">>}]},{resp_body,<<>>},{onresponse,#Fun}]},{state,{context,undefined,none,undefined}}],[{cowboy_rest,is_authorized,2,[{file,"src/cowboy_rest.erl"},{line,150}]},{cowboy_protocol,execute,4,[{file,"src/cowboy_protocol.erl"},{line,442}]}]}

答:
I am not sure when/how I missed it, but I had to run (rerun?)

rabbitmq-plugins enable rabbitmq_auth_backend_ldap

After this, the authentication worked.

Body:
Morning,

I clustered two servers and it was working with rabbitmq.config that used just the ldap backend.  I tried to change it so it would use ldap just for authentication and internal for authorization, and I can log into the management console on the first server (rabbitmq01p).  However, if I try to access the 2nd server (rabbitmq02p) management console, it now throws:

Got response code 500 with body

This happens even with a test internal user radmin that I created.
I am not sure what needs to change.

The rabbitmq.config:

[
  {rabbit, [
    {loopback_users, []},
    {auth_backends, [{rabbit_auth_backend_ldap,
rabbit_auth_backend_internal}, rabbit_auth_backend_internal]},
    {log_levels, [{channel, info}, {connection, info}, {federation, info},
    mirroring, info}]},
    {tcp_listen_options,
         [binary,
         {packet,        raw},
         {reuseaddr,     true},
         {backlog,       128},
         {nodelay,       true},
         {exit_on_close, false}]
    },
    {default_user, <<"radmin">>},
    {default_pass, <<"radmin">>}

  ]},
  {kernel, [

  ]}
,
  {rabbitmq_management, [
    {listener, [
      {port, 15672}
    ]}
  ]}
   %% {listener, [{port,     12345},
   %%             {ip,       "127.0.0.1"},
   %%             {ssl,      true},
   %%             {ssl_opts, [{cacertfile, "/path/to/cacert.pem"},
   %%                         {certfile,   "/path/to/cert.pem"},
   %%                         {keyfile,    "/path/to/key.pem"}]}]},
,
{rabbitmq_auth_backend_ldap, [
    {other_bind, {"CN=LDAP Demo,OU=Generic and Shared
Accounts,OU=Admin,dc=usa,dc=company,dc=com", "password"}},
    {servers, ["ldap-server.company.com"]},
    {user_dn_lookup_attribute, "sAMAccountName"},
    {dn_lookup_base, "ou=User Accounts,ou=USA,DC=company,DC=com" },
    {user_dn_pattern, "${username}@usa.company.com" },
    {use_ssl, false},
    {port, 3268},
    {log,true},
    {group_lookup_base, "ou=Groups,dc=usa,dc=company,dc=com"},
    {tag_queries, [{administrator, {in_group, "CN=Server
Team,OU=Groups,DC=usa,DC=company,DC=com"}},
                   {management,    {constant, true}}]}
   ]
  }
].

The error in the log:

=ERROR REPORT==== 13-Nov-2017::09:03:26 ===
Ranch listener rabbit_web_dispatch_sup_15672 had connection process started with cowboy_protocol:start_link/4 at <0.1234.0> exit with reason: {[{reason,{badmatch,undefined}},{mfa,{rabbit_mgmt_wm_whoami,is_authorized,2}},{stacktrace,[{rabbit_auth_backend_ldap,env,1,[{file,"src/rabbit_auth_backend_ldap.erl"},{line,580}]},{rabbit_auth_backend_ldap,log,2,[{file,"src/rabbit_auth_backend_ldap.erl"},{line,721}]},{rabbit_auth_backend_ldap,user_login_authentication,2,[{file,"src/rabbit_auth_backend_ldap.erl"},{line,74}]},{rabbit_access_control,try_authenticate,3,[{file,"src/rabbit_access_control.erl"},{line,88}]},{rabbit_access_control,'-check_user_login/2-fun-0-',4,[{file,"src/rabbit_access_control.erl"},{line,65}]},{lists,foldl,3,[{file,"lists.erl"},{line,1248}]},{rabbit_mgmt_util,is_authorized,6,[{file,"src/rabbit_mgmt_util.erl"},{line,160}]},{cowboy_rest,call,3,[{file,"src/cowboy_rest.erl"},{line,976}]}]},{req,[{socket,#Port<0.25192>},{transport,ranch_tcp},{connection,keepalive},{pid,<0.1234.0>},{method,<<"GET">>},{version,'HTTP/1.1'},{peer,{{10,2,2,144},52823}},{host,<<"esrabbitmq02p.usa.company.com">>},{host_info,undefined},{port,15672},{path,<<"/api/whoami">>},{path_info,undefined},{qs,<<>>},{qs_vals,[]},{bindings,[]},{headers,[{<<"host">>,<<"esrabbitmq02p.usa.company.com:15672">>},{<<"connection">>,<<"keep-alive">>},{<<"user-agent">>,<<"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36">>},{<<"authorization">>,<<"Basic cmFkbWpzOnJhZG1pbg==">>},{<<"content-type">>,<<"application/json">>},{<<"accept">>,<<"/">>},{<<"referer">>,<<"http://esrabbitmq02p.usa.company.com:15672/">>},{<<"accept-encoding">>,<<"gzip, deflate">>},{<<"accept-language">>,<<"en-US,en;q=0.8">>},{<<"cookie">>,<<"_SI_VID_1.681cceba2200012815576dcc=3bafef640f2a946d6f48e512; _vwo_uuid_v2=5707BE963C1A8F85D47ABE721862DCD2|e694e7c388bfb2dd860621dc71c082fc; _ceg.s=ow9umn; _ceg.u=ow9umn; RDTC=1; __utmz=234506268.1505479911.21.2.utmcsr=favorites.usa.company.com|utmccn=(referral)|utmcmd=referral|utmcct=/; _SI_VID_3.681cceba2200012815576dcc=3bafef640f2a946d6f48e512; LPVID=lmMWNkODgyOWJiMDYzN2Jk; rxVisitor=15053163485147G3CS2HA9NUHJFVP185Q0ASL8J4DDIV2; amlbcookie=03; iPlanetDirectoryPro=AQIC5wM2LY4Sfcyx28ueXpdDc1glrOUlOpBpriQ5JrEN_3Y.AAJTSQACMDIAAlNLABMtNjg0NTczODcxNTgzMTczMjU1AAJTMQACMDM.; __utma=234506268.404039322.1499344780.1509745463.1510321495.40; __utmc=234506268; _ga=GA1.2.404039322.1499344780; m=2258:cmFkbWluOnJhZG1pbg%253D%253D">>}]},{p_headers,[{<<"connection">>,[<<"keep-alive">>]}]},{cookies,undefined},{meta,[]},{body_state,waiting},{buffer,<<>>},{multipart,undefined},{resp_compress,true},{resp_state,waiting},{resp_headers,[{<<"vary">>,<<"origin">>}]},{resp_body,<<>>},{onresponse,#Fun}]},{state,{context,undefined,none,undefined}}],[{cowboy_rest,is_authorized,2,[{file,"src/cowboy_rest.erl"},{line,150}]},{cowboy_protocol,execute,4,[{file,"src/cowboy_protocol.erl"},{line,442}]}]}


问:
Parse xml - empty element
I have problem with parse XML, this is my xml:

```<code><Invoice version="6.0.1">
   <DocumentType>1</DocumentType>
   <ID>FV17116113</ID>
   <InvoiceLines>
      <InvoiceLine>
         <UnitPrice>25</UnitPrice>
      </InvoiceLine>
      <InvoiceLine>
         <UnitPrice>55</UnitPrice>
      </InvoiceLine>
   </InvoiceLines>
</Invoice>
</code>```

i try this code:

```<code>XmlDocument xml= new XmlDocument();
xml.Load(sourcexml);
foreach (XmlElement row in xml.DocumentElement.SelectNodes("InvoiceLines/InvoiceLine"))
{
}
</code>```

But i have nothing in element row....
Have you any idea please?

答:
I actually cannot understand your problem?
I guess you should remove xmlns attribute from your Invoice node.

Remove this

```<code>xmlns="http://isdoc.cz/namespace/2013"
</code>```

Then, your code will work

```<code>  foreach (XmlElement row in xml.DocumentElement.SelectNodes("InvoiceLines/InvoiceLine"))
            {
                Console.WriteLine(row.InnerText);
            }
</code>```

Title: Parse xml - empty element

Body:
I have problem with parse XML, this is my xml:

<Invoice version="6.0.1">
   <DocumentType>1</DocumentType>
   <ID>FV17116113</ID>
   <InvoiceLines>
      <InvoiceLine>
         <UnitPrice>25</UnitPrice>
      </InvoiceLine>
      <InvoiceLine>
         <UnitPrice>55</UnitPrice>
      </InvoiceLine>
   </InvoiceLines>
</Invoice>

i try this code:

XmlDocument xml= new XmlDocument();
xml.Load(sourcexml);
foreach (XmlElement row in xml.DocumentElement.SelectNodes("InvoiceLines/InvoiceLine"))
{
}

But i have nothing in element row....
Have you any idea please?

Body:
I actually cannot understand your problem?
I guess you should remove xmlns attribute from your Invoice node.

Remove this

xmlns="http://isdoc.cz/namespace/2013"

Then, your code will work

  foreach (XmlElement row in xml.DocumentElement.SelectNodes("InvoiceLines/InvoiceLine"))
            {
                Console.WriteLine(row.InnerText);
            }


问:
'read binary' on files vs. 'join' on strings in Python 2.7
I'm re-writing an older script which generates a lot of temporary files for saving and exchanging information/data between functions. I want to keep them  as variables, to avoid the overhead of generating files.

My problem: I encountered a function in which two files are merged on a binary level using this code:

```<code>with open(first_file, "ab") as file1, open(second_file, "rb") as file2:
        file1.write(file2.read())
</code>```

I would like to do the same, using strings and the '.join' function like this:

```<code>first_file = ''.join([first_file, second_file])
</code>```

My question: is the .join function equivalent to 'read binary'? Or does the 'read binary' mode even apply to .join?

The data I'm working on is binary, so the simple 'read' command would potentially alter the contents.

So far I found this info in the official Python documentation:

Python on Windows makes a distinction between text and binary files;
  the end-of-line characters in text files are automatically altered
  slightly when data is read or written. This behind-the-scenes
  modification to file data is fine for ASCII text files, but it’ll
  corrupt binary data like that in JPEG or EXE files.

答:
Read-binary is somewhat similar to using r"somestring" to indicate raw strings - the underlying file is binary, you're just telling Python to skip trying to decode the binary data into ASCII or UTF-8 or what-have-you characters.

So, the mode doesn't really apply here.

Since join operates on strings, you'd need to open file A, read it as a string, then do the same for B, whereas the original code just needs to read B and seek to the end of file A to start writing. So, you're not really getting much mileage out of doing a str.join, and you're actually using more memory.

If you want to optimize, make a loop that reads B line by line with writes it - that allows you to load just one line's worth of memory at a time rather than dumping the whole B file into it all at once.

Body:
I'm re-writing an older script which generates a lot of temporary files for saving and exchanging information/data between functions. I want to keep them  as variables, to avoid the overhead of generating files.

My problem: I encountered a function in which two files are merged on a binary level using this code:

with open(first_file, "ab") as file1, open(second_file, "rb") as file2:
        file1.write(file2.read())

I would like to do the same, using strings and the '.join' function like this:

first_file = ''.join([first_file, second_file])

My question: is the .join function equivalent to 'read binary'? Or does the 'read binary' mode even apply to .join?

The data I'm working on is binary, so the simple 'read' command would potentially alter the contents.

So far I found this info in the official Python documentation:

Python on Windows makes a distinction between text and binary files;
  the end-of-line characters in text files are automatically altered
  slightly when data is read or written. This behind-the-scenes
  modification to file data is fine for ASCII text files, but it’ll
  corrupt binary data like that in JPEG or EXE files.


问:
Unit Testing a method that calls a stored procedure and returns the results
I have a question about unit testing.  I have a method that takes in 2 date time parameters : start time, and end time.  The method calls a database and returns a set of records between the the 2 date times.  I have been told to unit test this logic, but I am not sure how.  My first try was to directly call the database and qry the table in question.  Then call the method.  Lastly I would compare the 2 results and see if they are the same.

It does not make sense to me to test this method because all of the logic is in the database.  I could moq a few basic objects, but then all I would be testing would be if my fake data is returned.  i.e. pass in x, get back y, results not null would pass.  I might be on the wrong track here so I could use some advice please.

答:
If you have logic in your database that you want to unit test, then unfortunately, you only really have three options:

Extract the logic into a service and unit test that (this has the consequence of a potentially large quantity of rework)

Call the procedure in the unit test inside a transaction and rollback (this has the drawback that you are dependant on a database existing and slows down your unit tests)

SQL Server has a facility to use shared classes inside its stored procedures - so you can unit test that code in isolation.

I've previously written on this subject, so you might find that useful.


问:
Strange behavior with cell construction with Simple TableView Swift
I have spent an insane time to fix this bug in our application. We are currently working in a chat and we have used a tableview for it.

Our tableview works fine until there is a certain amount of messages, after that, the table starts to flick. I coded without storyboards and for this reason I thought that constraints were the cause of trouble. So I decide to make a really simple tableview with some features of our chat tableview (actually our tableview is coredata linked and with a lot of graphic stuffs).

Because I suspected about constraints, I didn't use it in the code bellow just to see everything works fine, but it wasn't the case. In the gif image we can see two undesirable behaviors, the first one is that sometimes the table is re-generated completely, so cells disappear and appear in a very short time (this cause a very annoying flick). The second is no less annoying: cells are duplicated (I think this is for the cell reusability feature) but after a short period of time they are accommodated and everything goes fine.

https://github.com/hugounavez/pizzaWatch/blob/master/videoBug.gif

I tried adding the prepareForReuse() method and delete the views and creates them in the cell again but no results.

This is the example code, you can copy and run it with no problems in a Playground:

```<code>//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class Modelito{
    // This is the class tableview model
    var celda: String
    var valor: String
    init(celda: String, valor: String){
        self.celda = celda
        self.valor = valor
    }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    let tableview: UITableView = {
        let table = UITableView()
        table.translatesAutoresizingMaskIntoConstraints = false
        return table
    }()

    let button: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Click me to add new cell", for: .normal)
        button.setTitle("Click me to add new cell", for: .highlighted)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    var model: [Modelito] = []

    let tipoDeCelda = ["MyCustomCell", "MyCustomCell2"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupViews()

        self.tableview.register(MyCustomCell.self, forCellReuseIdentifier: "MyCustomCell")
        self.tableview.register(MyCustomCell2.self, forCellReuseIdentifier: "MyCustomCell2")

        self.tableview.dataSource = self
        self.tableview.delegate = self

        self.button.addTarget(self, action: #selector(self.addRow), for: .touchUpInside)

        // Here I generate semi random info
        self.dataGeneration()
    }

    func setupViews(){

        self.view.addSubview(self.tableview)
        self.tableview.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.tableview.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -50).isActive = true
        self.tableview.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 1).isActive = true
        self.tableview.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

        self.tableview.backgroundColor = .gray

        self.view.addSubview(self.button)
        self.button.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        self.button.topAnchor.constraint(equalTo: self.tableview.bottomAnchor).isActive = true
        self.button.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        self.button.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        self.button.backgroundColor = .orange

    }

    func dataGeneration(){
        let number = 200
        // Based in the cell types availables and the senteces, we create random cell info
        for _ in 0...number{

            self.model.append(
                Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
            )
        }

        self.tableview.reloadData()
        // After we insert elements in the model we scroll table
        let indexPaths: [IndexPath] = [IndexPath(row: self.model.count - 1, section: 0)]
        self.tableview.scrollToRow(at: indexPaths[0], at: .bottom, animated: false)
    }

    @objc func addRow(){
        // This function insert a new random element
        self.tableview.beginUpdates()
        self.model.append(
            Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
        )

        // After inserting the element in the model, we insert it in the tableview
        let indexPaths: [IndexPath] = [IndexPath(row: self.model.count - 1, section: 0)]
        self.tableview.insertRows(at: indexPaths, with: .none)
        self.tableview.endUpdates()
        // Finally we scroll to last row
        self.tableview.scrollToRow(at: indexPaths[0], at: .bottom, animated: false)

    }

}

extension ViewController{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.model.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let celldata = self.model[indexPath.row]

        switch celldata.celda {
        case "MyCustomCell":
            let cell = tableview.dequeueReusableCell(withIdentifier: "MyCustomCell", for: indexPath) as! MyCustomCell
            cell.myLabel.text = self.model[indexPath.row].valor
            return cell
        default:
            let cell = tableview.dequeueReusableCell(withIdentifier: "MyCustomCell2", for: indexPath) as! MyCustomCell2
            cell.myLabel.text = self.model[indexPath.row].valor
            return cell
        }

    }
}

class MyCustomCell: UITableViewCell {

    var myLabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        myLabel.backgroundColor = UIColor.green
        self.contentView.addSubview(myLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        myLabel.frame = CGRect(x: 25, y: 0, width: 370, height: 30)
    }
}

class MyCustomCell2: UITableViewCell {

    var myLabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        myLabel.backgroundColor = UIColor.yellow
        self.contentView.addSubview(myLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        myLabel.frame = CGRect(x: 0, y: 0, width: 370, height: 30)
    }

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = ViewController()
</code>```

Thanks in advance.

Edit:

I changed the code base in the @Scriptable answer in order to be compatible with playground. At this point, I am starting to think that duplication cell bug is actually normal for tableview. In order to see the problem, the button should be pressed several times fastly.

答:
This code is reloading the tableview but it's removing that "annoying flick" and it's too smooth.

To fix that annoying flick just change addRow() function to

```<code>   @objc func addRow(){

    self.model.append(
        Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
    )
    self.tableview.reloadData()
    self.scrollToBottom()
}
</code>```

scrollToBottom() function:

```<code>func scrollToBottom(){
    DispatchQueue.global(qos: .background).async {
        let indexPath = IndexPath(row: self.model.count-1, section: 0)
        self.tableview.scrollToRow(at: indexPath, at: .bottom, animated: true)
    }
}
</code>```

Just try it.

Body:
I have spent an insane time to fix this bug in our application. We are currently working in a chat and we have used a tableview for it.

Our tableview works fine until there is a certain amount of messages, after that, the table starts to flick. I coded without storyboards and for this reason I thought that constraints were the cause of trouble. So I decide to make a really simple tableview with some features of our chat tableview (actually our tableview is coredata linked and with a lot of graphic stuffs).

Because I suspected about constraints, I didn't use it in the code bellow just to see everything works fine, but it wasn't the case. In the gif image we can see two undesirable behaviors, the first one is that sometimes the table is re-generated completely, so cells disappear and appear in a very short time (this cause a very annoying flick). The second is no less annoying: cells are duplicated (I think this is for the cell reusability feature) but after a short period of time they are accommodated and everything goes fine.

https://github.com/hugounavez/pizzaWatch/blob/master/videoBug.gif

I tried adding the prepareForReuse() method and delete the views and creates them in the cell again but no results.

This is the example code, you can copy and run it with no problems in a Playground:

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class Modelito{
    // This is the class tableview model
    var celda: String
    var valor: String
    init(celda: String, valor: String){
        self.celda = celda
        self.valor = valor
    }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    let tableview: UITableView = {
        let table = UITableView()
        table.translatesAutoresizingMaskIntoConstraints = false
        return table
    }()

    let button: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Click me to add new cell", for: .normal)
        button.setTitle("Click me to add new cell", for: .highlighted)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    var model: [Modelito] = []

    let tipoDeCelda = ["MyCustomCell", "MyCustomCell2"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupViews()

        self.tableview.register(MyCustomCell.self, forCellReuseIdentifier: "MyCustomCell")
        self.tableview.register(MyCustomCell2.self, forCellReuseIdentifier: "MyCustomCell2")

        self.tableview.dataSource = self
        self.tableview.delegate = self

        self.button.addTarget(self, action: #selector(self.addRow), for: .touchUpInside)

        // Here I generate semi random info
        self.dataGeneration()
    }

    func setupViews(){

        self.view.addSubview(self.tableview)
        self.tableview.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.tableview.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -50).isActive = true
        self.tableview.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 1).isActive = true
        self.tableview.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

        self.tableview.backgroundColor = .gray

        self.view.addSubview(self.button)
        self.button.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        self.button.topAnchor.constraint(equalTo: self.tableview.bottomAnchor).isActive = true
        self.button.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        self.button.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        self.button.backgroundColor = .orange

    }

    func dataGeneration(){
        let number = 200
        // Based in the cell types availables and the senteces, we create random cell info
        for _ in 0...number{

            self.model.append(
                Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
            )
        }

        self.tableview.reloadData()
        // After we insert elements in the model we scroll table
        let indexPaths: [IndexPath] = [IndexPath(row: self.model.count - 1, section: 0)]
        self.tableview.scrollToRow(at: indexPaths[0], at: .bottom, animated: false)
    }

    @objc func addRow(){
        // This function insert a new random element
        self.tableview.beginUpdates()
        self.model.append(
            Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
        )

        // After inserting the element in the model, we insert it in the tableview
        let indexPaths: [IndexPath] = [IndexPath(row: self.model.count - 1, section: 0)]
        self.tableview.insertRows(at: indexPaths, with: .none)
        self.tableview.endUpdates()
        // Finally we scroll to last row
        self.tableview.scrollToRow(at: indexPaths[0], at: .bottom, animated: false)

    }

}

extension ViewController{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.model.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let celldata = self.model[indexPath.row]

        switch celldata.celda {
        case "MyCustomCell":
            let cell = tableview.dequeueReusableCell(withIdentifier: "MyCustomCell", for: indexPath) as! MyCustomCell
            cell.myLabel.text = self.model[indexPath.row].valor
            return cell
        default:
            let cell = tableview.dequeueReusableCell(withIdentifier: "MyCustomCell2", for: indexPath) as! MyCustomCell2
            cell.myLabel.text = self.model[indexPath.row].valor
            return cell
        }

    }
}

class MyCustomCell: UITableViewCell {

    var myLabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        myLabel.backgroundColor = UIColor.green
        self.contentView.addSubview(myLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        myLabel.frame = CGRect(x: 25, y: 0, width: 370, height: 30)
    }
}

class MyCustomCell2: UITableViewCell {

    var myLabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        myLabel.backgroundColor = UIColor.yellow
        self.contentView.addSubview(myLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        myLabel.frame = CGRect(x: 0, y: 0, width: 370, height: 30)
    }

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = ViewController()

Thanks in advance.

Edit:

I changed the code base in the @Scriptable answer in order to be compatible with playground. At this point, I am starting to think that duplication cell bug is actually normal for tableview. In order to see the problem, the button should be pressed several times fastly.

Body:
This code is reloading the tableview but it's removing that "annoying flick" and it's too smooth.

To fix that annoying flick just change addRow() function to

   @objc func addRow(){

    self.model.append(
        Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
    )
    self.tableview.reloadData()
    self.scrollToBottom()
}

scrollToBottom() function:

func scrollToBottom(){
    DispatchQueue.global(qos: .background).async {
        let indexPath = IndexPath(row: self.model.count-1, section: 0)
        self.tableview.scrollToRow(at: indexPath, at: .bottom, animated: true)
    }
}

Just try it.


问:
jQuery $(this) works in Firefox; fails the second time in Internet Explorer?
My little jQuery snippet works great in Firefox; but fails in IE.  This is particularly annoying and mysterious because a very similar command, just a few lines earlier, does work in IE.  Any ideas?</p>

```<code>$('.bio_text').clone()
   .each ( function(index, value) {
     name = $(this).find('.lc_name').text();
       // Prior line works just fine

     name = '<span class="lc_name">' + name + '</span>';
     title = $(this).find('.lc_title').text();
       // Prior line fails in IE and doesn't execute anything further,
       //  as determined by sprinkling alert() statements after every line

     title = '<div class="lc_title">' + title + '</div>';
     $('<li>' + name + title + '</li>').appendTo('ul#nav_team');
    });
</code>```

答:
Internet Explorer will throw errors if you don't declare variables before assigning values to them.

You might want to try declaring your variables like this

```<code>   ...
   var name = $(this).find('.lc_name').text();
   ...
   var title = $(this).find('.lc_title').text();
   ...
</code>```

Body:
My little jQuery snippet works great in Firefox; but fails in IE.  This is particularly annoying and mysterious because a very similar command, just a few lines earlier, does work in IE.  Any ideas?

$('.bio_text').clone()
   .each ( function(index, value) {
     name = $(this).find('.lc_name').text();
       // Prior line works just fine

     name = '' + name + '';
     title = $(this).find('.lc_title').text();
       // Prior line fails in IE and doesn't execute anything further,
       //  as determined by sprinkling alert() statements after every line

     title = '
' + title + '
';
     $('
' + name + title + '
').appendTo('ul#nav_team');
    });

Body:
Internet Explorer will throw errors if you don't declare variables before assigning values to them.

You might want to try declaring your variables like this

   ...
   var name = $(this).find('.lc_name').text();
   ...
   var title = $(this).find('.lc_title').text();
   ...


问:
QML combobox showing incorrect value
```<code>ComboBox {
    anchors.fill: parent
    model: rangeList
    currentIndex: 1
}
</code>```

rangeList contains 1,2,3 as data and currentIndex is 1. But when I run the UI it always takes currentindex as 0. Can anyone tell why it is taking currentIndex as 0 instead of 1.

```<code>ListModel { id: rangeList
    ListElement { name: "1" }
    ListElement { name: "2" }
    ListElement { name: "3" }
    ListElement { name: "4" }
}
</code>```

答:
You can try setting the index using onCompleted which is emitted after the object has been instantiated.

```<code>ComboBox {
    anchors.fill: parent
    model: rangeList
    Component.onCompleted: currentIndex = 1
}
</code>```

Title: QML combobox showing incorrect value

Body:
ComboBox {
    anchors.fill: parent
    model: rangeList
    currentIndex: 1
}

rangeList contains 1,2,3 as data and currentIndex is 1. But when I run the UI it always takes currentindex as 0. Can anyone tell why it is taking currentIndex as 0 instead of 1.

ListModel { id: rangeList
    ListElement { name: "1" }
    ListElement { name: "2" }
    ListElement { name: "3" }
    ListElement { name: "4" }
}

Body:
You can try setting the index using onCompleted which is emitted after the object has been instantiated.

ComboBox {
    anchors.fill: parent
    model: rangeList
    Component.onCompleted: currentIndex = 1
}


问:
Xcode "Device Locked" When iPhone is unlocked
When I tried to build and run, Xcode said my device was locked. I looked at my iPhone, and it's not locked at all. How do I fix this?</p>

答:
This issue is not about "Trust" or not. It's a bug in Xcode.

Just follow these steps.

When Xcode is running and your device is connected:

Lock your device.

Unplug your device from Mac.

Unlock your device.

Plug your device back to Mac.