问:
Why am I getting runtime errors, with Sockets (TCP/Web) when moved to another thread? Is `QObject::moveToThread()` a synchronous call?
I am moving some sockets from main thread to worker thread and processing readyRead(), close(), write() etc. on the new thread. Rarely I see below dangerous warning:

"QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread"

Usually the execution after this warning results in undefined behaviour (crash / uncaught exception / normal).

Have checked all the signal/slot to the socket and they seem proper. From my experience, usually the above warning will be frequent or quick if there is any coding irregularity.

Now I am suspecting if moveToThread() does its job as expected or not! Because from QEvent documentation a QEvent::ThreadChange is raised as the last event on the current thread during this function call.

The object is moved to another thread. This is the last event sent to this object in the previous thread. See QObject::moveToThread()1.

  1 A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. You can handle this event to perform any special processing.

In my code, I am not checking for this event. Rather I assume that, once the moveToThread() is finished, the thread affinity is changed and the new "signal/slot" on the object is guaranteed on the new thread.

Question:

Is it safe to move the sockets to another thread?

Will moveToThread() assure that the signals on that object are also moved to the new thread just after this function?

How should it be designed to assure no threading irregularity with Sockets?

BTW, in the latest Qt debugger it lands on following code segment:

```<code>// qsocketnotifier.cpp
if (Q_UNLIKELY(thread() != QThread::currentThread())) {
    qWarning("QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread");
    return;
}
</code>```

Below is the stack frame for the main thread:

Below is the stack frame for the worker thread, which halts on the logging:

答:
Qt sockets are NOT supported with moveToThread() idiom!!!

I wish Qt had documented this fact as LOUD as above. I have spent weeks of debugging an issue which is not meant for fixing. Socket moveToThread() issue is so complicated, that it doesn't happen consistently. I could reproduce it consistently only after testing a customised QTcpServer subclass with lots of socket open/close scenario.

Later I came across this post: How do I execute QTcpSocket in a different thread?. This answer explicitly states that sockets are not supported for the movement across the threads.

Here are the documentations from QTcpServer

Note: The returned QTcpSocket object cannot be used from another thread. If you want to use an incoming connection from another thread, you need to override incomingConnection().

Note: If you want to handle an incoming connection as a new QTcpSocket object in another thread you have to pass the "socketDescriptor" to the other thread and create the QTcpSocket object there and use its setSocketDescriptor() method.

Probably this will apply to the QWebSocketServer too!

So the best approach is to overload incomingConnection() and call its internal in another thread.

```<code>void MyTcpServer::incomingConnection (qintptr socketDescriptor) override
{
  emit SignalToDifferentThread(socketDescriptor);
}
</code>```

If done so, the addPendingConnection() and nextPendingConnection() idiom may not be required, even though it's mentioned in a note.

Note: If another socket is created in the reimplementation of this method, it needs to be added to the Pending Connections mechanism by calling addPendingConnection().  (<-- this may not apply for the sockets in different thread)

QWebSocketServer is stricter than QTcpServer

This is another fact, which wasted more time for me. In QTcpServer, we can overload the incomingConnection() and pass on the socket descriptor to another thread to create a socket. However, QWebSocketServer doesn't have such overload. Mostly because, QSslSocket received in QTcpServer gets upgraded to QWebSocket and passed on to the QWebSocketServer via its handleConnection() method.

So QWebSocket must be created where QWebSocketServer resides!. Hence in whichever threads, we want a QWebSocket to be created, all those threads need to have an object of QWebSocketServer. Idiomatically we can have one QTcpServer listening on a single port and can keep passing its QTcpSockets (upgraded to QWebSockets) to these various threads' QWebSocketServers in a load balancing way.

A message to Qt developers

I wish that, you can save lot of time of the developers relying on the Qt library by a simple compilation error. This will negate all the wrong articles floating around internet which suggest how to use moveToThread() on a QTcpSocket. Just introduce below method:

```<code>class QTcpServer / QTcpSocket / QWebSocketServer / QWebSocket : public QObject
{
  Q_OBJECT
  ...
  // Create this object in a desired thread instead of moving
  private: void moveToThread (QThread*) = delete; // hiding `QObject::moveToThread()`
};
</code>```

Update: Raised QTBUG-82373.

Body:
I am moving some sockets from main thread to worker thread and processing readyRead(), close(), write() etc. on the new thread. Rarely I see below dangerous warning:

"QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread"

Usually the execution after this warning results in undefined behaviour (crash / uncaught exception / normal).

Have checked all the signal/slot to the socket and they seem proper. From my experience, usually the above warning will be frequent or quick if there is any coding irregularity.

Now I am suspecting if moveToThread() does its job as expected or not! Because from QEvent documentation a QEvent::ThreadChange is raised as the last event on the current thread during this function call.

The object is moved to another thread. This is the last event sent to this object in the previous thread. See QObject::moveToThread()1.

  1 A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. You can handle this event to perform any special processing.

In my code, I am not checking for this event. Rather I assume that, once the moveToThread() is finished, the thread affinity is changed and the new "signal/slot" on the object is guaranteed on the new thread.

Question:

Is it safe to move the sockets to another thread?

Will moveToThread() assure that the signals on that object are also moved to the new thread just after this function?

How should it be designed to assure no threading irregularity with Sockets?

BTW, in the latest Qt debugger it lands on following code segment:

// qsocketnotifier.cpp
if (Q_UNLIKELY(thread() != QThread::currentThread())) {
    qWarning("QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread");
    return;
}

Below is the stack frame for the main thread:

Below is the stack frame for the worker thread, which halts on the logging:

Body:
Qt sockets are NOT supported with moveToThread() idiom!!!

I wish Qt had documented this fact as LOUD as above. I have spent weeks of debugging an issue which is not meant for fixing. Socket moveToThread() issue is so complicated, that it doesn't happen consistently. I could reproduce it consistently only after testing a customised QTcpServer subclass with lots of socket open/close scenario.

Later I came across this post: How do I execute QTcpSocket in a different thread?. This answer explicitly states that sockets are not supported for the movement across the threads.

Here are the documentations from QTcpServer

Note: The returned QTcpSocket object cannot be used from another thread. If you want to use an incoming connection from another thread, you need to override incomingConnection().

Note: If you want to handle an incoming connection as a new QTcpSocket object in another thread you have to pass the "socketDescriptor" to the other thread and create the QTcpSocket object there and use its setSocketDescriptor() method.

Probably this will apply to the QWebSocketServer too!

So the best approach is to overload incomingConnection() and call its internal in another thread.

void MyTcpServer::incomingConnection (qintptr socketDescriptor) override
{
  emit SignalToDifferentThread(socketDescriptor);
}

If done so, the addPendingConnection() and nextPendingConnection() idiom may not be required, even though it's mentioned in a note.

Note: If another socket is created in the reimplementation of this method, it needs to be added to the Pending Connections mechanism by calling addPendingConnection().  (<-- this may not apply for the sockets in different thread)

QWebSocketServer is stricter than QTcpServer

This is another fact, which wasted more time for me. In QTcpServer, we can overload the incomingConnection() and pass on the socket descriptor to another thread to create a socket. However, QWebSocketServer doesn't have such overload. Mostly because, QSslSocket received in QTcpServer gets upgraded to QWebSocket and passed on to the QWebSocketServer via its handleConnection() method.

So QWebSocket must be created where QWebSocketServer resides!. Hence in whichever threads, we want a QWebSocket to be created, all those threads need to have an object of QWebSocketServer. Idiomatically we can have one QTcpServer listening on a single port and can keep passing its QTcpSockets (upgraded to QWebSockets) to these various threads' QWebSocketServers in a load balancing way.

A message to Qt developers

I wish that, you can save lot of time of the developers relying on the Qt library by a simple compilation error. This will negate all the wrong articles floating around internet which suggest how to use moveToThread() on a QTcpSocket. Just introduce below method:

class QTcpServer / QTcpSocket / QWebSocketServer / QWebSocket : public QObject
{
  Q_OBJECT
  ...
  // Create this object in a desired thread instead of moving
  private: void moveToThread (QThread*) = delete; // hiding `QObject::moveToThread()`
};

Update: Raised QTBUG-82373.


来源: stackexchange

问:
How to use "ref" to refer an element in React Stateless Component
I was trying to implement focus for the Submit button with Ref. I wanted to omit refering elements by ID.

```<code>import React, { useRef } from 'react'
import PropTypes from 'prop-types'

export const LabelComponent = () => {

  const createButton = enableCreateButton()
    ? <button ref={(input) => { this.createLabelBtn = input }} >Submit</button>
    : <button disabled ref={(input) => { this.createLabelBtn = input }} >Submit</button>

  const createLabelBtn = useRef();

  const focusCreateBtn = (e) => {
    if ((e.key === 'Enter') && (newLabel.name !== '')) {
      this.createLabelBtn.focus();
    }
  };

  return (
    <div className='create-label-container'>
      <input type='text'
        onKeyDown={(e) => { focusCreateBtn(e) }}
      />

      {createButton}
    </div>
  )
}
</code>```

It gives following error.

Uncaught TypeError: Cannot set property 'createLabelBtn' of undefined

Uncaught TypeError: Cannot set property 'createLabelBtn' of undefined

What could be the issue here.?

答:
Functional components are instanceless, therefore, no this to bind anything to or call upon. Set the ref prop on the button as so ref={createLabelBtn}, and to set the focus you need to access createLabelBtn.current to get at the current value of the ref.

```<code>export const LabelComponent = ({ enableCreateButton }) => {
  const createLabelBtn = useRef(null);

  const focusCreateBtn = e => {
    if (e.key === "Enter") {
      createLabelBtn.current.focus();
    }
  };

  return (
    <div className="create-label-container">
      <input type="text" onKeyDown={focusCreateBtn} />
      <button
        // upon being focused upon, console log proof
        onFocus={() => console.log("Submit Focused!")}
        disabled={!enableCreateButton}
        ref={createLabelBtn}
      >
        Submit
      </button>
    </div>
  );
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was trying to implement focus for the Submit button with Ref. I wanted to omit refering elements by ID.

import React, { useRef } from 'react'
import PropTypes from 'prop-types'

export const LabelComponent = () => {

  const createButton = enableCreateButton()
    ? <button ref={(input) => { this.createLabelBtn = input }} >Submit</button>
    : <button disabled ref={(input) => { this.createLabelBtn = input }} >Submit</button>

  const createLabelBtn = useRef();

  const focusCreateBtn = (e) => {
    if ((e.key === 'Enter') && (newLabel.name !== '')) {
      this.createLabelBtn.focus();
    }
  };

  return (

      <input type='text'
        onKeyDown={(e) => { focusCreateBtn(e) }}
      />

      {createButton}

  )
}

It gives following error.

Uncaught TypeError: Cannot set property 'createLabelBtn' of undefined

Uncaught TypeError: Cannot set property 'createLabelBtn' of undefined

What could be the issue here.?

Body:
Functional components are instanceless, therefore, no this to bind anything to or call upon. Set the ref prop on the button as so ref={createLabelBtn}, and to set the focus you need to access createLabelBtn.current to get at the current value of the ref.

export const LabelComponent = ({ enableCreateButton }) => {
  const createLabelBtn = useRef(null);

  const focusCreateBtn = e => {
    if (e.key === "Enter") {
      createLabelBtn.current.focus();
    }
  };

  return (
    <div className="create-label-container">
      <input type="text" onKeyDown={focusCreateBtn} />
      <button
        // upon being focused upon, console log proof
        onFocus={() => console.log("Submit Focused!")}
        disabled={!enableCreateButton}
        ref={createLabelBtn}
      >
        Submit
      </button>
    </div>
  );
};


问:
Migrating MOSS 2007 from SQL 2000 to SQL 2005 - Addendum
This is a continuation of an earlier question I had about moving the databases for a MOSS 2007 installation from SQL 2000 to SQL 2005.  Here's the URL for the original question:  Migrating MOSS 2007 from SQL 2000 to SQL 2005

In my test environment, I've successfully moved the databases to the SQL 2005 test machine and things appear to be working fine.  But, on the "Servers in Farm" page of the Central Admin | Operations, it still shows the old (i.e. SQL 2000) server as the Configuration Database Server.  Also, it shows the old config database as being the Configuration Database.  I know that the SQL2000 server and old config database (that are showing on this page) are NOT being used, because we've deactived the SQL instance in SQL2000.

I've tried "removing" the server, and get a message about "Uninstalling SharePoint products and technologies" being the better route.  So, I disconnected from the test databases, uninstalled SharePoint from the test WFE server, and reinstalled it.  That didn't do anything.  Before uninstalling/reinstalling I also tried simply rerunning the SharePoint Configuration wizard, and that didn't do anything either.

Does anyone know how to update the Config Server and Config Database on the "Servers in Farm" page after having moved the Config and Content DBs?  Is there something I'm missing or overlooking?

Thanks.

答:
```<code>stsadm setconfigdb
</code>```

?

```<code>stsadm -help setconfigdb
</code>```

shows:

```
stsadm.exe -o setconfigdb
           [-connect]
           -databaseserver
           [-databaseuser ]
           [-databasepassword ]
           [-databasename ]
           [-hh]
           [-adcreation]
           [-addomain ]
           [-adou ]
```

Also see Technet which says PSConfig has superseded stsadm.

ContentLicense: CC BY-SA 2.5

Body:
stsadm setconfigdb

?

stsadm -help setconfigdb

shows:

stsadm.exe -o setconfigdb
           [-connect]
           -databaseserver
           [-databaseuser ]
           [-databasepassword ]
           [-databasename ]
           [-hh]
           [-adcreation]
           [-addomain ]
           [-adou ]

Also see Technet which says PSConfig has superseded stsadm.

OwnerDisplayName: Richard


问:
$(document).ready called inside an external function?
I saw some jquery code on the Net somewhere, that took this form :

```<code><script>
function doSomething(message)
{
    $(document).ready(function(){
        alert(message);
        });
};
</script>
</code>```

i.e. an external function ("doSomething") which has $(document).ready inside it. I'm confused because isn't the code under $(document).ready triggered when the DOM is loaded ? Its like having an event handler inside a function (?). Does this form of code make sense to anyone ? Thanks.

答: It was probably an error on the part of the original coder. You could do that, but you'd want to call doSomething pretty early on. Note that if the DOM is already ready when you call ready, jQuery will call the code, so it will happen either way, but it won't happen until someone, somewhere, calls doSomething. I can't see much purpose to the pattern, so unless you have some strong argument for using it — and given the question, I suspect you don't :-) — you can safely ignore it.

ContentLicense: CC BY-SA 3.0

Body:
I saw some jquery code on the Net somewhere, that took this form :

i.e. an external function ("doSomething") which has $(document).ready inside it. I'm confused because isn't the code under $(document).ready triggered when the DOM is loaded ? Its like having an event handler inside a function (?). Does this form of code make sense to anyone ? Thanks.


问:
AlertDialog not working in thread Android
I get an error about to much activity on main thread when I try to print to a Bluetooth printer. I tried to change it to use a thread but then my AlterDialog does not work.
Is there another way to make it work where I can display the AlterDialog?
Thanks.</p>

```<code>public class PrinterFunctions{

private static void sendCommand(final Context context,final String portName, final String portSettings, final ArrayList<Byte> byteList) {

    new Thread() {
        @Override
        public void run() {
            StarIOPort port = null;

            try {

                port = StarIOPort.getPort(portName, portSettings, 10000, context);

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }

                StarPrinterStatus status = port.beginCheckedBlock();

                if (true == status.offline) {
                    throw new StarIOPortException("A printer is offline");
                }

                byte[] commandToSendToPrinter = convertFromListByteArrayTobyteArray(byteList);
                port.writePort(commandToSendToPrinter, 0,
                        commandToSendToPrinter.length);

                port.setEndCheckedBlockTimeoutMillis(30000);
                status = port.endCheckedBlock();

                if (true == status.coverOpen) {
                    throw new StarIOPortException("Printer cover is open");
                } else if (true == status.receiptPaperEmpty) {
                    throw new StarIOPortException("Receipt paper is empty");
                } else if (true == status.offline) {
                    throw new StarIOPortException("Printer is offline");
                }
            } catch (StarIOPortException e) {
                Builder dialog = new AlertDialog.Builder(context);
                dialog.setNegativeButton("Ok", null);
                AlertDialog alert = dialog.create();
                alert.setTitle("Failure");
                alert.setMessage(e.getMessage());
                alert.setCancelable(false);
                alert.show();
            } finally {
                if (port != null) {
                    try {
                        StarIOPort.releasePort(port);
                    } catch (StarIOPortException e) {
                    }
                }
            }
        }
    }
  }.start();

}
}
</code>```

答:
I know this is an old post but I just want to help those who will end up here.

I will create a new thread just for the alert dialog inside the existing thread?

Technically you're not creating a new thread but calling the Main thread to create your alert dialog because you're currently inside you're background thread.

So for your dialog to pop up you need the Main thread execute your alert dialog command.

try to replace

```<code>                dialog.setNegativeButton("Ok", null);
                AlertDialog alert = dialog.create();
                alert.setTitle("Failure");
                alert.setMessage(e.getMessage());
                alert.setCancelable(false);
                alert.show();
</code>```

with

```<code>runOnUiThread(new Runnable()
{
    @Override
    public void run()
    {
        Builder dialog = new AlertDialog.Builder(context);
                dialog.setNegativeButton("Ok", null);
                AlertDialog alert = dialog.create();
                alert.setTitle("Failure");
                alert.setMessage(e.getMessage());
                alert.setCancelable(false);
                alert.show();
    });
</code>```

or you can use a handler

protected Handler handler = new Handler(Loop.getMainLooper)

```<code>handler.post(new Runnable()
{
    @Override
    public void run()
    {
        Builder dialog = new AlertDialog.Builder(context);
                dialog.setNegativeButton("Ok", null);
                AlertDialog alert = dialog.create();
                alert.setTitle("Failure");
                alert.setMessage(e.getMessage());
                alert.setCancelable(false);
                alert.show();
    });
</code>```

Body:
I get an error about to much activity on main thread when I try to print to a Bluetooth printer. I tried to change it to use a thread but then my AlterDialog does not work.
Is there another way to make it work where I can display the AlterDialog?
Thanks.

public class PrinterFunctions{

private static void sendCommand(final Context context,final String portName, final String portSettings, final ArrayList<Byte> byteList) {

    new Thread() {
        @Override
        public void run() {
            StarIOPort port = null;

            try {

                port = StarIOPort.getPort(portName, portSettings, 10000, context);

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }

                StarPrinterStatus status = port.beginCheckedBlock();

                if (true == status.offline) {
                    throw new StarIOPortException("A printer is offline");
                }

                byte[] commandToSendToPrinter = convertFromListByteArrayTobyteArray(byteList);
                port.writePort(commandToSendToPrinter, 0,
                        commandToSendToPrinter.length);

                port.setEndCheckedBlockTimeoutMillis(30000);
                status = port.endCheckedBlock();

                if (true == status.coverOpen) {
                    throw new StarIOPortException("Printer cover is open");
                } else if (true == status.receiptPaperEmpty) {
                    throw new StarIOPortException("Receipt paper is empty");
                } else if (true == status.offline) {
                    throw new StarIOPortException("Printer is offline");
                }
            } catch (StarIOPortException e) {
                Builder dialog = new AlertDialog.Builder(context);
                dialog.setNegativeButton("Ok", null);
                AlertDialog alert = dialog.create();
                alert.setTitle("Failure");
                alert.setMessage(e.getMessage());
                alert.setCancelable(false);
                alert.show();
            } finally {
                if (port != null) {
                    try {
                        StarIOPort.releasePort(port);
                    } catch (StarIOPortException e) {
                    }
                }
            }
        }
    }
  }.start();

}
}

Body:
I know this is an old post but I just want to help those who will end up here.

I will create a new thread just for the alert dialog inside the existing thread?

Technically you're not creating a new thread but calling the Main thread to create your alert dialog because you're currently inside you're background thread.

So for your dialog to pop up you need the Main thread execute your alert dialog command.

try to replace

                dialog.setNegativeButton("Ok", null);
                AlertDialog alert = dialog.create();
                alert.setTitle("Failure");
                alert.setMessage(e.getMessage());
                alert.setCancelable(false);
                alert.show();

with

runOnUiThread(new Runnable()
{
    @Override
    public void run()
    {
        Builder dialog = new AlertDialog.Builder(context);
                dialog.setNegativeButton("Ok", null);
                AlertDialog alert = dialog.create();
                alert.setTitle("Failure");
                alert.setMessage(e.getMessage());
                alert.setCancelable(false);
                alert.show();
    });

or you can use a handler

protected Handler handler = new Handler(Loop.getMainLooper)

handler.post(new Runnable()
{
    @Override
    public void run()
    {
        Builder dialog = new AlertDialog.Builder(context);
                dialog.setNegativeButton("Ok", null);
                AlertDialog alert = dialog.create();
                alert.setTitle("Failure");
                alert.setMessage(e.getMessage());
                alert.setCancelable(false);
                alert.show();
    });


问:
Java Access Bridge c# unable to activate field, set text, click etc
I am working on the Java Access Bridge in c# for some time now.
I finally got it to working, partly.

I can properly initialize the access bridge.

I can use the GetAccessibleContextFromHWND to get vmid and javaObjectHandle.

I can also use GetAccessibleContextInfo to get accessibleContextInfo.

Lastly, I can enumerate the children and find a node that interests me.

How do I take it from there?
I tried to do things like set text, click or get text but was unable.
I used the below code that was mentioned in another question, Automation using Java Access Bridge

Set text:

```<code>public string Text
{
    get
    {
        return GetText();
    }
    set
    {
        if (!API.setTextContents(this.VmId, this.Context, value))
            throw new AccessibilityException("Error setting text");
    }
}

private string GetText()
{
    System.Text.StringBuilder sbText = new System.Text.StringBuilder();

    int caretIndex = 0;

    while (true)
    {
        API.AccessibleTextItemsInfo ti = new API.AccessibleTextItemsInfo();
        if (!API.getAccessibleTextItems(this.VmId, this.Context, ref ti, caretIndex))
            throw new AccessibilityException("Error getting accessible text item information");

        if (!string.IsNullOrEmpty(ti.sentence))
            sbText.Append(ti.sentence);
        else
            break;

        caretIndex = sbText.Length;

    }
</code>```

Click on a button:

```<code>public void Press()
{
    DoAction("click");
}

protected void DoAction(params string[] actions)
{
    API.AccessibleActionsToDo todo = new API.AccessibleActionsToDo()
    {
        actionInfo = new API.AccessibleActionInfo[API.MAX_ACTIONS_TO_DO],
        actionsCount = actions.Length,
    };

    for (int i = 0, n = Math.Min(actions.Length, API.MAX_ACTIONS_TO_DO); i < n; i++)
        todo.actionInfo[i].name = actions[i];

    Int32 failure = 0;
    if (!API.doAccessibleActions(this.VmId, this.Context, ref todo, ref failure))
        throw new AccessibilityException("Error performing action");
}
</code>```

Any ideas would be much appreciated.
Thanks!!

答: doAccessibleActions actually this function is not working at all, so, you must combine win32 api for doing alternative such as: set text => send key, scroll ...

Body:
I am working on the Java Access Bridge in c# for some time now.
I finally got it to working, partly.

I can properly initialize the access bridge.

I can use the GetAccessibleContextFromHWND to get vmid and javaObjectHandle.

I can also use GetAccessibleContextInfo to get accessibleContextInfo.

Lastly, I can enumerate the children and find a node that interests me.

How do I take it from there?
I tried to do things like set text, click or get text but was unable.
I used the below code that was mentioned in another question, Automation using Java Access Bridge

Set text:

public string Text
{
    get
    {
        return GetText();
    }
    set
    {
        if (!API.setTextContents(this.VmId, this.Context, value))
            throw new AccessibilityException("Error setting text");
    }
}

private string GetText()
{
    System.Text.StringBuilder sbText = new System.Text.StringBuilder();

    int caretIndex = 0;

    while (true)
    {
        API.AccessibleTextItemsInfo ti = new API.AccessibleTextItemsInfo();
        if (!API.getAccessibleTextItems(this.VmId, this.Context, ref ti, caretIndex))
            throw new AccessibilityException("Error getting accessible text item information");

        if (!string.IsNullOrEmpty(ti.sentence))
            sbText.Append(ti.sentence);
        else
            break;

        caretIndex = sbText.Length;

    }

Click on a button:

public void Press()
{
    DoAction("click");
}

protected void DoAction(params string[] actions)
{
    API.AccessibleActionsToDo todo = new API.AccessibleActionsToDo()
    {
        actionInfo = new API.AccessibleActionInfo[API.MAX_ACTIONS_TO_DO],
        actionsCount = actions.Length,
    };

    for (int i = 0, n = Math.Min(actions.Length, API.MAX_ACTIONS_TO_DO); i < n; i++)
        todo.actionInfo[i].name = actions[i];

    Int32 failure = 0;
    if (!API.doAccessibleActions(this.VmId, this.Context, ref todo, ref failure))
        throw new AccessibilityException("Error performing action");
}

Any ideas would be much appreciated.
Thanks!!


问:
Django - template - reduce for loop repetition, reduce sqlite3 db query
I find myself repeatedly cycling through the same set of data, accessing database several time for the same loops to achieve displaying the correct data on one template, here's the code:

                    {% for image in item.itemimage_set.all %}

                    {% endfor %}

                    {% for image in item.itemimage_set.all %}

                    {% endfor %}

                {% if item.itemimage_set.count > 1 %}

                    Previous

                    Next

                {% endif %}

            {% for image in item.itemimage_set.all %}

 3 %}
            col-sm-6
            {% else %}
            col-sm-8
            {% endif %}
            mt-2 px-1 mt-sm-0 pb-sm-2 pt-sm-0 mb-0">

            {% endfor %}

```

<h3>The above code renders the item's <code>itemimage</code> bootstrap carousel and on the same page, an extra carousel modal:</h3>

<pre class="lang-html prettyprint-override"><code><!-- itemImageModal -->
<div class="modal fade" id="itemImageModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle"
    aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered col-12 col-md-8 modal-lg" role="document">
        <div class="modal-content">
            <div class="col-12 px-0">
                <div id="itemImage{{item.pk}}Carousel" class="carousel slide" data-ride="carousel">

                    <ol class="carousel-indicators">
                        {% for image in item.itemimage_set.all %}
                        <li data-target="#itemImage{{item.pk}}Carousel" data-slide-to="{{forloop.counter0}}"
                                {% if forloop.first %} class="active" {% endif %}></li>
                        {% endfor %}
                    </ol>

                    <div class="carousel-inner shadow-lg rounded-sm">

                        {% for image in item.itemimage_set.all %}
                        <div class="carousel-item {% if forloop.first %} active {% endif %}">
                            <img src="{{image.image.url}}" class="d-block w-100" alt="...">
                        </div>
                        {% endfor %}

                    </div>

                    {% if item.itemimage_set.count > 1 %}

                        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                        <span class="sr-only">Previous</span>

                        <span class="carousel-control-next-icon" aria-hidden="true"></span>
                        <span class="sr-only">Next</span>

                    {% endif %}

                </div>

            </div>
        </div>
    </div>
</div>
</code>```

Data structure:

class Item(models.Model):
    name = ... etc.

class ItemImage(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='itemimages', null=True, blank=True)
```

<h3>As you can see, there are 5 forloop cycles in the template which leads to frequent queries from the database over the same set of data.</h3>

<hr>

<h2>What I've tried:</h2>

<p>I've tried to replace <code>{% for image in item.itemimage_set.all %}</code> with <code>{% for image in item.load_related_itemimage %}</code>, and in the <code>models.py</code>:</p>

<pre class="lang-py prettyprint-override"><code>class Item(models.Model):
    name = ...

    def load_related_itemimage(self):
        return self.itemimage_set.prefetch_related('image')
</code>```

and this prompt error:

'image' does not resolve to an item that supports prefetching - this is an invalid parameter to prefetch_related().

I'm actually quite new to django and am not sure how to use select_related or prefetch_related but so far I've employed them and managed to reduce database query from 150 to 30+. And I think the frequency can be further reduced due to the silly cycles above as you can see.

forward the Debug Toolbar data for the page:

```<code>SELECT "appname_itemimage"."id",
       "appname_itemimage"."item_id",
       "appname_itemimage"."image"
  FROM "appname_itemimage"
 WHERE "appname_itemimage"."item_id" = '19'
  5 similar queries.   Duplicated 5 times.
</code>```

5 similar queries.   Duplicated 5 times. is bad right?

view.py

class ItemDetailView(DetailView):
    '''display an individual item'''
    model = Item
    template_name = 'boutique/item.html'
```

<hr>

<h3>Thanks for @Iain Shelvington's answer, his solution for the above code works like a charm, how about this:</h3>

<p>I think they are related so I didn't separate this to raise another question -- what if the <code>item</code> itself is in a forloop? how to use <code>prefetch_related</code> in this situation? thanks!</p>

<pre class="lang-html prettyprint-override"><code>{% for item in subcategory.item_set.all %}

<img src="{{ item.itemimage_set.first.image.url }}">

{% endfor %}
</code>```

because I need to access item.itemimage_set when looping through subcateogry.item_set, and this is a much worse problem than before, because it raises 19 repetition in loading itemimage

This template is rendered by a ListView

class CategoryListView(ListView):
    '''display a list of items'''
    model = Category
    # paginate_by = 1
    template_name = 'boutique/show_category.html'
    context_object_name = 'category_shown'

    def get_queryset(self):
        qs = super().get_queryset().get_categories_with_item()
        self.gender = self.kwargs.get('gender')  # reuse in context
        gender = self.gender
        request = self.request

        # fetch filter-form data
        self.category_selected = request.GET.get('category_selected')
        self.brand_selected = request.GET.get('brand_selected')
        self.min_price = request.GET.get('min_price')
        self.max_price = request.GET.get('max_price')

        if gender == 'women':
            self.gender_number = 1
        elif gender == 'men':
            self.gender_number = 2
        else:
            raise Http404

        get_category_selected = Category.objects.filter(
            gender=self.gender_number, name__iexact=self.category_selected).first()
        category_selected_pk = get_category_selected.pk if get_category_selected else None

        get_subcategory_selected = SubCategory.objects.filter(
            category__gender=self.gender_number, name__iexact=self.category_selected).first()
        subcategory_selected_pk = get_subcategory_selected.pk if get_subcategory_selected else None

        category_pk = category_selected_pk if category_selected_pk else self.kwargs.get(
            'category_pk')
        subcategory_pk = subcategory_selected_pk if subcategory_selected_pk else self.kwargs.get(
            'subcategory_pk')

        # print('\nself.kwargs:\n', gender, category_pk, subcategory_pk)

        if gender and not category_pk and not subcategory_pk:
            qs = qs.get_categories_by_gender(gender)
            # print('\nCategoryLV_qs_gender= ', '\n', qs, '\n', gender, '\n')
            return qs

        elif gender and category_pk:
            qs = qs.filter(pk=category_pk)
            # print('\nCategoryLV_qs_category= ', '\n', qs, '\n')
            return qs

        elif gender and subcategory_pk:
            qs = SubCategory.objects.annotate(Count('item')).exclude(
                item__count=0).filter(pk=subcategory_pk)
            self.context_object_name = 'subcategory_shown'
            # print('\nCategoryLV_qs_sub_category= ', '\n', qs, '\n')
            return qs

    def get_validated_cats(self):
        categories_validated = []
        subcategories_validated = []
        items_validated = []

        brand_selected = self.brand_selected
        min_price = self.min_price
        if min_price == '' or min_price is None:
            min_price = 0
        max_price = self.max_price
        if max_price == '' or max_price is None:
            max_price = 999999

        for item in Item.objects.select_related('category', 'subcategory', 'tag').filter(category__gender=self.gender_number):
            if int(min_price) <= item.final_price < int(max_price):
                if brand_selected is None or brand_selected == 'бренд' or item.brand.name == brand_selected:
                    items_validated.append(item)
                    if item.category not in categories_validated:
                        categories_validated.append(item.category)
                    if item.subcategory not in subcategories_validated:
                        subcategories_validated.append(item.subcategory)

        return categories_validated, subcategories_validated, items_validated

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['brands'] = Brand.objects.all()

        cat_valid, subcat_valid, items_valid = self.get_validated_cats()
        context['filter_context'] = {
            'gender': self.gender,
            'gender_number': self.gender_number,
            'category_selected': self.category_selected,
            'brand_selected': self.brand_selected,
            'min_price': self.min_price,
            'max_price': self.max_price,
            'categories_validated': cat_valid,
            'subcategories_validated': subcat_valid,
            'items_validated': items_valid,
        }

        # print(context)
        return context
```

答:
You should use prefetch_related to prefetch "itemimage_set" so that every time you access item.itemimage_set.all you get the cached result

```<code>item = get_object_or_404(Item.objects.prefetch_related('itemimage_set'), pk=pk)
</code>```

For a DetailView

```<code>class ItemDetailView(DetailView):
    model = Item
    queryset = Item.objects.prefetch_related('itemimage_set')
</code>```

Body:
I find myself repeatedly cycling through the same set of data, accessing database several time for the same loops to achieve displaying the correct data on one template, here's the code:

                    {% for image in item.itemimage_set.all %}

                    {% endfor %}

                    {% for image in item.itemimage_set.all %}

                    {% endfor %}

                {% if item.itemimage_set.count > 1 %}

                    Previous

                    Next

                {% endif %}

            {% for image in item.itemimage_set.all %}

 3 %}
            col-sm-6
            {% else %}
            col-sm-8
            {% endif %}
            mt-2 px-1 mt-sm-0 pb-sm-2 pt-sm-0 mb-0">

            {% endfor %}

The above code renders the item's itemimage bootstrap carousel and on the same page, an extra carousel modal:

                        {% for image in item.itemimage_set.all %}

                        {% endfor %}

                        {% for image in item.itemimage_set.all %}

                        {% endfor %}

                    {% if item.itemimage_set.count > 1 %}

                        Previous

                        Next

                    {% endif %}

Data structure:

class Item(models.Model):
    name = ... etc.

class ItemImage(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='itemimages', null=True, blank=True)

As you can see, there are 5 forloop cycles in the template which leads to frequent queries from the database over the same set of data.

What I've tried:

I've tried to replace {% for image in item.itemimage_set.all %} with {% for image in item.load_related_itemimage %}, and in the models.py:

class Item(models.Model):
    name = ...

    def load_related_itemimage(self):
        return self.itemimage_set.prefetch_related('image')

and this prompt error:

'image' does not resolve to an item that supports prefetching - this is an invalid parameter to prefetch_related().

I'm actually quite new to django and am not sure how to use select_related or prefetch_related but so far I've employed them and managed to reduce database query from 150 to 30+. And I think the frequency can be further reduced due to the silly cycles above as you can see.

forward the Debug Toolbar data for the page:

SELECT "appname_itemimage"."id",
       "appname_itemimage"."item_id",
       "appname_itemimage"."image"
  FROM "appname_itemimage"
 WHERE "appname_itemimage"."item_id" = '19'
  5 similar queries.   Duplicated 5 times.

5 similar queries.   Duplicated 5 times. is bad right?

view.py

class ItemDetailView(DetailView):
    '''display an individual item'''
    model = Item
    template_name = 'boutique/item.html'

Thanks for @Iain Shelvington's answer, his solution for the above code works like a charm, how about this:

I think they are related so I didn't separate this to raise another question -- what if the item itself is in a forloop? how to use prefetch_related in this situation? thanks!

{% for item in subcategory.item_set.all %}

{% endfor %}

because I need to access item.itemimage_set when looping through subcateogry.item_set, and this is a much worse problem than before, because it raises 19 repetition in loading itemimage

This template is rendered by a ListView

class CategoryListView(ListView):
    '''display a list of items'''
    model = Category
    # paginate_by = 1
    template_name = 'boutique/show_category.html'
    context_object_name = 'category_shown'

    def get_queryset(self):
        qs = super().get_queryset().get_categories_with_item()
        self.gender = self.kwargs.get('gender')  # reuse in context
        gender = self.gender
        request = self.request

        # fetch filter-form data
        self.category_selected = request.GET.get('category_selected')
        self.brand_selected = request.GET.get('brand_selected')
        self.min_price = request.GET.get('min_price')
        self.max_price = request.GET.get('max_price')

        if gender == 'women':
            self.gender_number = 1
        elif gender == 'men':
            self.gender_number = 2
        else:
            raise Http404

        get_category_selected = Category.objects.filter(
            gender=self.gender_number, name__iexact=self.category_selected).first()
        category_selected_pk = get_category_selected.pk if get_category_selected else None

        get_subcategory_selected = SubCategory.objects.filter(
            category__gender=self.gender_number, name__iexact=self.category_selected).first()
        subcategory_selected_pk = get_subcategory_selected.pk if get_subcategory_selected else None

        category_pk = category_selected_pk if category_selected_pk else self.kwargs.get(
            'category_pk')
        subcategory_pk = subcategory_selected_pk if subcategory_selected_pk else self.kwargs.get(
            'subcategory_pk')

        # print('\nself.kwargs:\n', gender, category_pk, subcategory_pk)

        if gender and not category_pk and not subcategory_pk:
            qs = qs.get_categories_by_gender(gender)
            # print('\nCategoryLV_qs_gender= ', '\n', qs, '\n', gender, '\n')
            return qs

        elif gender and category_pk:
            qs = qs.filter(pk=category_pk)
            # print('\nCategoryLV_qs_category= ', '\n', qs, '\n')
            return qs

        elif gender and subcategory_pk:
            qs = SubCategory.objects.annotate(Count('item')).exclude(
                item__count=0).filter(pk=subcategory_pk)
            self.context_object_name = 'subcategory_shown'
            # print('\nCategoryLV_qs_sub_category= ', '\n', qs, '\n')
            return qs

    def get_validated_cats(self):
        categories_validated = []
        subcategories_validated = []
        items_validated = []

        brand_selected = self.brand_selected
        min_price = self.min_price
        if min_price == '' or min_price is None:
            min_price = 0
        max_price = self.max_price
        if max_price == '' or max_price is None:
            max_price = 999999

        for item in Item.objects.select_related('category', 'subcategory', 'tag').filter(category__gender=self.gender_number):
            if int(min_price) <= item.final_price < int(max_price):
                if brand_selected is None or brand_selected == 'бренд' or item.brand.name == brand_selected:
                    items_validated.append(item)
                    if item.category not in categories_validated:
                        categories_validated.append(item.category)
                    if item.subcategory not in subcategories_validated:
                        subcategories_validated.append(item.subcategory)

        return categories_validated, subcategories_validated, items_validated

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['brands'] = Brand.objects.all()

        cat_valid, subcat_valid, items_valid = self.get_validated_cats()
        context['filter_context'] = {
            'gender': self.gender,
            'gender_number': self.gender_number,
            'category_selected': self.category_selected,
            'brand_selected': self.brand_selected,
            'min_price': self.min_price,
            'max_price': self.max_price,
            'categories_validated': cat_valid,
            'subcategories_validated': subcat_valid,
            'items_validated': items_valid,
        }

        # print(context)
        return context

Body:
You should use prefetch_related to prefetch "itemimage_set" so that every time you access item.itemimage_set.all you get the cached result

item = get_object_or_404(Item.objects.prefetch_related('itemimage_set'), pk=pk)

For a DetailView

class ItemDetailView(DetailView):
    model = Item
    queryset = Item.objects.prefetch_related('itemimage_set')


答:
Does this form of code make sense to anyone ?

No, it doesn't.

Title: $(document).ready called inside an external function?


问:
Hosting multiple ASP NET Core sites on unbuntu and nginx as reverse proxy
I am trying to host multiple ASP NET Core sites with different domains on Linux, Unbunt 18.04 and using nginx as reverse proxy.

These are the steps:

1) Creating new .conf files in /etc/nginx/sites-available

2) Creating folders in /var/www/ and uploadin the .net app

3) Creating new .service files for each .conf file

The default nginx .conf is unchanged.

The .conf files look like this:

```<code>server {
    listen        80;
    server_name   domain;
    location / {
        proxy_pass         http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

</code>```

The .service files look like this:

```<code>[Unit]
Description=Event Registration Example

[Service]
WorkingDirectory=/var/www/example
ExecStart=/usr/bin/dotnet /var/www/example/example.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target
</code>```

With this configuration, even I deploy few sites, all of them are redirected to same content. My goal is to host multiple .net core apps on same server.
How the configuration should look like?

答:
Individual ports on the server is the way to go, in ASP.NET Core 3.0 my program.cs looks like this:</p>

```<code>public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(serverOptions =>
                {

                    serverOptions.Listen(IPAddress.Loopback, 5100);

                })
                .UseStartup<Startup>();
            });
}
</code>```

Body:
I am trying to host multiple ASP NET Core sites with different domains on Linux, Unbunt 18.04 and using nginx as reverse proxy.

These are the steps:

1) Creating new .conf files in /etc/nginx/sites-available

2) Creating folders in /var/www/ and uploadin the .net app

3) Creating new .service files for each .conf file

The default nginx .conf is unchanged.

The .conf files look like this:

server {
    listen        80;
    server_name   domain;
    location / {
        proxy_pass         http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

The .service files look like this:

[Unit]
Description=Event Registration Example

[Service]
WorkingDirectory=/var/www/example
ExecStart=/usr/bin/dotnet /var/www/example/example.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

With this configuration, even I deploy few sites, all of them are redirected to same content. My goal is to host multiple .net core apps on same server.
How the configuration should look like?

Body:
Individual ports on the server is the way to go, in ASP.NET Core 3.0 my program.cs looks like this:

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(serverOptions =>
                {

                    serverOptions.Listen(IPAddress.Loopback, 5100);

                })
                .UseStartup<Startup>();
            });
}


问:
how to fix " Could not resolve type" error with MySQL connector in dotnet Core
I'm trying to build a dotnet Core application which connects to my mysql data.
This works fine for a dotnet Framework (on Windows), and dotNetCore (on Windows), but when I try it from dotNet Core (on Linux) I get an error saying:

System.TypeLoadException: Could not resolve type with token 010000fd from typeref (expected class 'System.Security.PermissionSet' in assembly 'System.Security.Permissions, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51')
    at MySql.Data.MySqlClient.MySqlConnection.Open ()

My csproj file contains this:

```<code>  <ItemGroup>
<PackageReference Include="AWSSDK.Kinesis" Version="3.3.100.38" />
<PackageReference Include="AWSSDK.Lambda" Version="3.3.19.24" />
<PackageReference Include="AWSSDK.S3" Version="3.3.3" />
<PackageReference Include="AWSSDK.SimpleNotificationService" Version="3.3.3.26" />
<PackageReference Include="AWSSDK.SQS" Version="3.3.3.62" />
<PackageReference Include="CoreCLR-NCalc" Version="2.2.51" />
<PackageReference Include="Disruptor" Version="3.6.1" />
<PackageReference Include="ExcelDna.Integration" Version="0.34.6" />
<PackageReference Include="MathNet.Numerics" Version="4.7.0" />
<PackageReference Include="Microsoft.CodeAnalysis" Version="2.10.0" />
<PackageReference Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" Version="2.0.1" />
<PackageReference Include="Microsoft.Office.Interop.Excel" Version="15.0.4795.1000" />
<PackageReference Include="Mono.Data.Sqlite" Version="1.0.61" />
<PackageReference Include="MySql.Data" Version="8.0.19" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Parquet.Net" Version="3.2.4" />
<PackageReference Include="protobuf-net" Version="2.4.0" />
<PackageReference Include="System.CodeDom" Version="4.7.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.7.0" />
<PackageReference Include="System.Data.SQLite" Version="1.0.112" />
<PackageReference Include="System.IO.Compression" Version="4.3.0" />
<PackageReference Include="unofficial.sevenziplib.codeplex" Version="9.13.5" />
 </ItemGroup>
</code>```

How do I fix?

答:
In my .net core projects, I use the Pomelo.EntityFrameworkCore.MySql package for connecting with MySQL which works fine for me.

You might want to check it out if the problem persists with the current plugin.

https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql

Body:
I'm trying to build a dotnet Core application which connects to my mysql data.
This works fine for a dotnet Framework (on Windows), and dotNetCore (on Windows), but when I try it from dotNet Core (on Linux) I get an error saying:

System.TypeLoadException: Could not resolve type with token 010000fd from typeref (expected class 'System.Security.PermissionSet' in assembly 'System.Security.Permissions, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51')
    at MySql.Data.MySqlClient.MySqlConnection.Open ()

My csproj file contains this:

  <ItemGroup>
<PackageReference Include="AWSSDK.Kinesis" Version="3.3.100.38" />
<PackageReference Include="AWSSDK.Lambda" Version="3.3.19.24" />
<PackageReference Include="AWSSDK.S3" Version="3.3.3" />
<PackageReference Include="AWSSDK.SimpleNotificationService" Version="3.3.3.26" />
<PackageReference Include="AWSSDK.SQS" Version="3.3.3.62" />
<PackageReference Include="CoreCLR-NCalc" Version="2.2.51" />
<PackageReference Include="Disruptor" Version="3.6.1" />
<PackageReference Include="ExcelDna.Integration" Version="0.34.6" />
<PackageReference Include="MathNet.Numerics" Version="4.7.0" />
<PackageReference Include="Microsoft.CodeAnalysis" Version="2.10.0" />
<PackageReference Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" Version="2.0.1" />
<PackageReference Include="Microsoft.Office.Interop.Excel" Version="15.0.4795.1000" />
<PackageReference Include="Mono.Data.Sqlite" Version="1.0.61" />
<PackageReference Include="MySql.Data" Version="8.0.19" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Parquet.Net" Version="3.2.4" />
<PackageReference Include="protobuf-net" Version="2.4.0" />
<PackageReference Include="System.CodeDom" Version="4.7.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.7.0" />
<PackageReference Include="System.Data.SQLite" Version="1.0.112" />
<PackageReference Include="System.IO.Compression" Version="4.3.0" />
<PackageReference Include="unofficial.sevenziplib.codeplex" Version="9.13.5" />
 </ItemGroup>

How do I fix?


问:
Return brace-enclosed initializer list as struct
Giving below simplified code compiled with g++ -c test.cpp or g++ -std=c++17 -c test.cpp

```<code>#include <cstddef>

struct sd_bus_vtable {
        union {
                struct {
                        size_t element_size;
                } start;
                struct {
                        const char *member;
                        const char *signature;
                } signal;
        } x;
};

sd_bus_vtable get()
{
    return {
        .x = {
            .signal = {
                .member = "",
                .signature= "",
            }
        }
    };
}
</code>```

It compiles fine on GCC 9.2.0 and clang 5/6, but fails on 8.3.0 or 7.4.0 with below error message:

```<code>test.cpp:25:5: error: could not convert ‘{{{"", ""}}}’ from ‘<brace-enclosed initializer list>’ to ‘sd_bus_vtable’
     };

</code>```

To work around it, the function get() could be changed as below, but it looks not so clean...

```<code>sd_bus_vtable get()
{
    struct sd_bus_vtable t = {
        .x = {
            .signal = {
                .member = "",
                .signature= "",
            }
        }
    };
    return t;
}
</code>```

The question is, is the above code valid or not? If yes, does it trigger some bug in GCC that is fixed in GCC9?

答:
The designated initializer syntax is not in Standard C++ yet. It is scheduled to be included in C++20 however that has not yet been finalized or published.

So you are relying on the compiler supporting this upcoming feature as an extension.

In published C++ standards there is no way to give an initializer like this for a union member other than the first one .   (You can have a default member initializer in the class definition).

In the meantime the following code would work:

```<code>sd_bus_vtable get()
{
    sd_bus_vtable r{};
    r.x.signal = {"", ""};
    return r;
}
</code>```

Note: This method (using the assignment operator to switch the active member of the union) only works if all of the union members have trivial constructors and destructors. Otherwise you need to manually destroy and create .

Also it's possible to omit the name x (this is called anonymous union), then the names of the union members are accessible as if they were members of the enclosing struct.

Body:
Giving below simplified code compiled with g++ -c test.cpp or g++ -std=c++17 -c test.cpp

#include <cstddef>

struct sd_bus_vtable {
        union {
                struct {
                        size_t element_size;
                } start;
                struct {
                        const char *member;
                        const char *signature;
                } signal;
        } x;
};

sd_bus_vtable get()
{
    return {
        .x = {
            .signal = {
                .member = "",
                .signature= "",
            }
        }
    };
}

It compiles fine on GCC 9.2.0 and clang 5/6, but fails on 8.3.0 or 7.4.0 with below error message:

test.cpp:25:5: error: could not convert ‘{{{"", ""}}}’ from ‘<brace-enclosed initializer list>’ to ‘sd_bus_vtable’
     };

To work around it, the function get() could be changed as below, but it looks not so clean...

sd_bus_vtable get()
{
    struct sd_bus_vtable t = {
        .x = {
            .signal = {
                .member = "",
                .signature= "",
            }
        }
    };
    return t;
}

The question is, is the above code valid or not? If yes, does it trigger some bug in GCC that is fixed in GCC9?

Body:
The designated initializer syntax is not in Standard C++ yet. It is scheduled to be included in C++20 however that has not yet been finalized or published.

So you are relying on the compiler supporting this upcoming feature as an extension.

In published C++ standards there is no way to give an initializer like this for a union member other than the first one .   (You can have a default member initializer in the class definition).

In the meantime the following code would work:

sd_bus_vtable get()
{
    sd_bus_vtable r{};
    r.x.signal = {"", ""};
    return r;
}

Note: This method (using the assignment operator to switch the active member of the union) only works if all of the union members have trivial constructors and destructors. Otherwise you need to manually destroy and create .

Also it's possible to omit the name x (this is called anonymous union), then the names of the union members are accessible as if they were members of the enclosing struct.


问:
Umbraco - How to import site images/aspx files easily like DotNetNuke?
I come from a DotNetNuke background. I have been able to get Umbraco to work, but I can only upload an image at a time etc. This is painfully slow because I have a large site. Other then using third party utilities is there anyway to speed up the upload process? Can I just drop the images in the media folder?</p>

答:
Dropping the files in the media folder will have no effect as the Media library (in Umbraco) will not know that they are there.

The easiest route is to use the excellent Desktop Media Uploader


问:
Typing a mapShape function in TypeScript
I want to use a utility function like this:

```<code>const out = mapShape(
  { foo: 1, bar: '2', baz: 'hello' },
  { foo: x => String(x), bar: x => parseInt(x) }
)
// outputs { foo: '1', bar: 2 }
</code>```

Is there a way to parameterize it in TypeScript so that the type of the output will be this?

```<code>{ foo: string, bar: number }
</code>```

I tried doing this:

```<code>export default function mapShape<
  I extends Record<any, any>,
  X extends { [K in keyof I]: (value: I[K], key: K, object: I) => any }
>(
  object: I,
  mapper: Partial<X>
): {
  [K in keyof I]: ReturnType<X[K]>
} {
  const result: any = {}
  for (const key in mapper) {
    if (Object.hasOwnProperty.call(mapper, key)) {
      result[key] = (mapper[key] as any)(object[key], key, object)
    }
  }
  return result
}
</code>```

However type TS infers for out is { foo: any, bar: any }; it doesn't infer specific types for the properties.

The following produces the correct output type, I'm just not sure if I can parameterize it:

```<code>const mappers = {
  foo: x => String(x),
  bar: x => parseInt(x),
}
type outputType = {
  [K in keyof typeof mappers]: ReturnType<typeof mappers[K]>
}
// { foo: string, bar: number }
</code>```

答:
I think the typing that behaves the best is something like this:

```<code>function mapShape<T extends { [K in keyof U]?: any }, U>(
    obj: T,
    mapper: { [K in keyof U]: K extends keyof T ? (x: T[K]) => U[K] : never }
): U {
    const result: any = {}
    for (const key in mapper) {
        if (Object.hasOwnProperty.call(mapper, key)) {
            result[key] = (mapper[key] as any)(obj[key], key, obj)
        }
    }
    return result
}
</code>```

I'm using inference from mapped types to allow the output type to be U and the mapper object to be a homomorphic mapped type on the keys of U.

This produces the desired output type for out while still inferring the parameter types in the callback properties of the mapper argument:

```<code>const out = mapShape(
    { foo: 1, bar: '2', baz: 'hello' },
    { foo: x => String(x), bar: x => parseInt(x) }
)
/* const out: {
    foo: string;
    bar: number;
} */
</code>```

It also should prevent adding properties to the mapper that don't exist in the object to be mapped:

```<code>const bad = mapShape(
    { a: 1 },
    { a: n => n % 2 === 0, x: n => n } // error!
    // ------------------> ~  ~ <----------
    // (n: any) => any is             implicit any
    // not never
)
</code>```

Okay, hope that helps you proceed; good luck!

Playground link to code

Body:
I want to use a utility function like this:

const out = mapShape(
  { foo: 1, bar: '2', baz: 'hello' },
  { foo: x => String(x), bar: x => parseInt(x) }
)
// outputs { foo: '1', bar: 2 }

Is there a way to parameterize it in TypeScript so that the type of the output will be this?

{ foo: string, bar: number }

I tried doing this:

export default function mapShape<
  I extends Record<any, any>,
  X extends { [K in keyof I]: (value: I[K], key: K, object: I) => any }
>(
  object: I,
  mapper: Partial<X>
): {
  [K in keyof I]: ReturnType<X[K]>
} {
  const result: any = {}
  for (const key in mapper) {
    if (Object.hasOwnProperty.call(mapper, key)) {
      result[key] = (mapper[key] as any)(object[key], key, object)
    }
  }
  return result
}

However type TS infers for out is { foo: any, bar: any }; it doesn't infer specific types for the properties.

The following produces the correct output type, I'm just not sure if I can parameterize it:

const mappers = {
  foo: x => String(x),
  bar: x => parseInt(x),
}
type outputType = {
  [K in keyof typeof mappers]: ReturnType<typeof mappers[K]>
}
// { foo: string, bar: number }

Body:
I think the typing that behaves the best is something like this:

function mapShape<T extends { [K in keyof U]?: any }, U>(
    obj: T,
    mapper: { [K in keyof U]: K extends keyof T ? (x: T[K]) => U[K] : never }
): U {
    const result: any = {}
    for (const key in mapper) {
        if (Object.hasOwnProperty.call(mapper, key)) {
            result[key] = (mapper[key] as any)(obj[key], key, obj)
        }
    }
    return result
}

I'm using inference from mapped types to allow the output type to be U and the mapper object to be a homomorphic mapped type on the keys of U.

This produces the desired output type for out while still inferring the parameter types in the callback properties of the mapper argument:

const out = mapShape(
    { foo: 1, bar: '2', baz: 'hello' },
    { foo: x => String(x), bar: x => parseInt(x) }
)
/* const out: {
    foo: string;
    bar: number;
} */

It also should prevent adding properties to the mapper that don't exist in the object to be mapped:

const bad = mapShape(
    { a: 1 },
    { a: n => n % 2 === 0, x: n => n } // error!
    // ------------------> ~  ~ <----------
    // (n: any) => any is             implicit any
    // not never
)

Okay, hope that helps you proceed; good luck!

<a href="http://www.typescriptlang.org/play/#code/GYVwdgxgLglg9mABAWwIYAcDKALDBTAHgBVE8APKPMAEwGdEBvRAbQGlEYkBrPATzmCIAqgF0A-AC5EqML0QBfADTCAfAAoAsAChEuxHABGAKylFF2vSgzo8AJylM2HbnwHCRU9uUo16PfoIkYohqZKZsIgCUiAC8KsIRiFJgeABudgrakVJCjBZ6EAi0UIi2eLQgADZQUjJyMYzy+brAcLYhhWDFiP7OVug2ttEMzZYcgmoA8sZ40AB0uLSTAO5gAAq2cINQvHMQqJWVamgDdsr+kcOjY3plFdXM-iKxISeDj3zPqPR1kWqGRg+vBE5z4ygBkWueiaOmhiFGZSgIFsSDuVSg2hh2m0nW6cBAJQaJxw+E0sN0TFacCkAEZlAZUPZEAByABMzPpqAAXlJmdg8Ic4MyFOZyYxEFSpGRYvFMFBbJwAOahSKcpnSuKIdCM2h4ACSYCgKsyWkhWhxRRKDOoL2JuBsZMsTFQtJFo2dyRliCQAFJEKzYjEGgAGZRhb1epDyRAAehjpFsm1sAEJRnHEABaLPZnO57PxAB+uiLBDzObT8bUYFqsmimrqHHoNxuMGQ6EqMAgMBKdQr3rgJRS6VsWSAA" rel="nofollow noreferrer">Playground link to code


问:
Count events in range on a vector via iteration in R
I have a vector that contains sample numbers of event markers. They are only listed when there is an event found, not at every sample. I would like to obtain an output of the number of events found every second. Sampling rate is known (15hz).

I figured out how to do it with a for loop, but it is working a bit on the slow side. I am struggling to figure out a more efficient way to perform this calculation (with mapply or something like that maybe?). Does anybody have any suggestions?

Here is a sample of what I am doing:

```<code>vec <- c(9,20,23,48,50,51)
fs <- 15
start_idx <- seq(from=1,to=46,by=15)
end_idx <- seq(from=15,to=60,by=15)
counter <- vector()
for (i in 1:length(start_idx)) {
  counter[i] <- length(which(vec >= start_idx[i] & vec <= end_idx[i]))
}
</code>```

The results of counter should be:

```<code>> counter
[1] 1 2 0 3
</code>```

Any help is much appreciated!

答:
You can use findInterval/cut to find element in vec lies in which range and then use table to count frequency.

```<code>table(factor(findInterval(vec, start_idx), levels = seq_along(start_idx)))
#1 2 3 4
#1 2 0 3
</code>```

Body:
I have a vector that contains sample numbers of event markers. They are only listed when there is an event found, not at every sample. I would like to obtain an output of the number of events found every second. Sampling rate is known (15hz).

I figured out how to do it with a for loop, but it is working a bit on the slow side. I am struggling to figure out a more efficient way to perform this calculation (with mapply or something like that maybe?). Does anybody have any suggestions?

Here is a sample of what I am doing:

vec <- c(9,20,23,48,50,51)
fs <- 15
start_idx <- seq(from=1,to=46,by=15)
end_idx <- seq(from=15,to=60,by=15)
counter <- vector()
for (i in 1:length(start_idx)) {
  counter[i] <- length(which(vec >= start_idx[i] & vec <= end_idx[i]))
}

The results of counter should be:

> counter
[1] 1 2 0 3

Any help is much appreciated!

Body:
You can use findInterval/cut to find element in vec lies in which range and then use table to count frequency.

table(factor(findInterval(vec, start_idx), levels = seq_along(start_idx)))
#1 2 3 4
#1 2 0 3


问:
How to modify numpy array by reference in a function?
I am trying to create a function which modifies a list of numpy arrays and converts them into a certain data type. I am having trouble mutating the numpy array.

Example:

```<code>>> a = ['1', '2']
>> convert(int, a)
>> a
a = [1, 2]
</code>```

This code works when the function is a regular array because d[:] refers to the array and not a copy.

```<code># data - data to be converted
# func - type of data
def convert(func, *data):
    for d in data:
        d[:] = list(map(func, d))
</code>```

This code does not work for some reason and I am puzzled as to why or how I can fix it.

```<code>def convert(func, *data):
    for d in data:
        d[:] = d.astype(func)
</code>```

Alternatively:

```<code>def convert(func, *data):
    for i in range(len(data)):
        data[i][:] = np.array( np.zeros(len(data[i]))) # works -> sets array outside function to 0s
        data[i][...] = data[i].astype(func) # doesn't work

</code>```

How would one do this within numpy?

答:
A string dtype array:

```<code>In [467]: b
Out[467]: array(['1', '2'], dtype='<U10')
</code>```

make a new array with int dtype:

```<code>In [468]: b.astype(int)
Out[468]: array([1, 2])
</code>```

Assigning those values back to b converts them back b's dtype:

```<code>In [469]: b[:] = b.astype(int)
In [470]: b
Out[470]: array(['1', '2'], dtype='<U10')
</code>```

astype makes a new array; you can't change the dtype of an array in-place.

===

By using *data, you just wrap the list or array in a tuple.  Pass in ['1','2'], and data becomes (['1', '2'],), anddis just that list.  The*data` and loop don't contribute anything to the problem (unless you want to convert several lists).

Body:
I am trying to create a function which modifies a list of numpy arrays and converts them into a certain data type. I am having trouble mutating the numpy array.

Example:

>> a = ['1', '2']
>> convert(int, a)
>> a
a = [1, 2]

This code works when the function is a regular array because d[:] refers to the array and not a copy.

# data - data to be converted
# func - type of data
def convert(func, *data):
    for d in data:
        d[:] = list(map(func, d))

This code does not work for some reason and I am puzzled as to why or how I can fix it.

def convert(func, *data):
    for d in data:
        d[:] = d.astype(func)

Alternatively:

def convert(func, *data):
    for i in range(len(data)):
        data[i][:] = np.array( np.zeros(len(data[i]))) # works -> sets array outside function to 0s
        data[i][...] = data[i].astype(func) # doesn't work

How would one do this within numpy?

Body:
A string dtype array:

In [467]: b
Out[467]: array(['1', '2'], dtype='<U10')

make a new array with int dtype:

In [468]: b.astype(int)
Out[468]: array([1, 2])

Assigning those values back to b converts them back b's dtype:

In [469]: b[:] = b.astype(int)
In [470]: b
Out[470]: array(['1', '2'], dtype='<U10')

astype makes a new array; you can't change the dtype of an array in-place.

===

By using *data, you just wrap the list or array in a tuple.  Pass in ['1','2'], and data becomes (['1', '2'],), anddis just that list.  The*data` and loop don't contribute anything to the problem (unless you want to convert several lists).


问:
Navigating back to start screen
I have two different documents with two different screens. After an e-mail validation on the first screen, I'm now able to go to the second screen. However, I want to return to the first screen. None of the mentioned approaches on the React Navigation 5.x documentation works for me.

This is the code on the App.js:

```<code>import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import firebase from './firebase';
import * as EmailValidator from 'email-validator';
import { HitTestResultTypes } from 'expo/build/AR';
import logo from './assets/Circulo.png';
import AgeInput from './AgeInput';

// Clase que representa el diseño de la pantalla inicial de la app
class HomeScreen extends Component {
  state = { username: null, password: null, nonValidInput: null }

  _onSubmit = ({ navigation }) =>{
    if(EmailValidator.validate(this.state.username) == true) {
      this.setState({ nonValidInput: false });
      const { username, password } = this.state;

      try {
        // THIS IS WHERE I GO TO THE SECOND SCREEN
        firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(() => this.props.navigation.navigate('Age'));
      } catch {
        Alert.alert(
          'Error',
          'Los datos no son correctos',
          [
            { text: 'Ok' }
          ],
          { cancelable: false }
        );
      }

    } else {
      this.setState({ nonValidInput: true });
    }
  }

  render() {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
      enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.logo}>
          <Image source = {logo} style={styles.img}/>
          <Text style={styles.textLogoPrimary}>Neuron App</Text>
          <Text style={styles.textLogoSecondary}>Test</Text>
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Correo Electrónico</Text>
          <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
          style={styles.formInput} />
          {this.state.nonValidInput ? (
            <Text style={styles.textAlert}>Correo electrónico no valido.</Text>
          ) : null}
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Contraseña</Text>
          <TextInput style={styles.formInput} placeholder='Contraseña' onChangeText={value => this.setState({ password: value })}
          secureTextEntry={true}/>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
            <Text style={styles.buttonText}>Iniciar</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

const Stack = createStackNavigator();

class App extends Component {
  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator screenOptions={{headerShown: false}} initialRouteName="Home">
          <Stack.Screen name='Home' component={HomeScreen} />
          <Stack.Screen name='Age' component={AgeInput} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}
</code>```

and this is the code on the AgeInput.js

```<code>import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Home from './App';

class App extends Component { // AgeInput
  state = { date: null, edad: null, day: null, month: null, year: null }

  _ageCalc = () => {
    if(this.state.day < 32 && this.state.day > 0 && this.state.month < 13 && this.state.month > 0 && this.state.year != 0) {
      var fecha = Date.parse(this.state.year + '-' + this.state.month + '-' + this.state.day);

      var hoy = new Date();
      var fechaNacimiento = new Date(fecha);
      var edad_ahora = hoy.getFullYear() - fechaNacimiento.getFullYear();
      var mes = hoy.getMonth() - fechaNacimiento.getMonth();

      if (mes < 0 || (mes === 0 && hoy.getDate() < fechaNacimiento.getDate())) {
        edad_ahora--;
      }

      this.setState({ edad: edad_ahora });
    } else {
      Alert.alert(
        'Error',
        'Por favor introduce una fecha valida',
        [
          { text: 'Ok' }
        ],
        { cancelable: false },
      );
    }
  }

  render () {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled enableOnAndroid={true}
      resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.topView}>
          // This is the button I press to go back to the first screen
          <TouchableOpacity style={styles.img} onPress={() => this.props.navigator.navigate('Home')}>
            <Image source={flecha} />
          </TouchableOpacity>
          <View style={styles.topTextWrapper}>
            <Text style={styles.topTextPrimary}>Bienvenido a Neuron</Text>
              <Text style={styles.topTextSecondary}>¿O no?</Text>
            </View>
        </View>

        <View style={styles.middleView}>
          <Text style={styles.formText}>Fecha de nacimiento</Text>
          <View style={styles.formRow}>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='DD' keyboardType='number-pad'
              onChangeText={ value => this.setState({ day: value }) }/>
            </View>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='MM' keyboardType='number-pad'
              onChangeText={ value => this.setState({ month: value }) }/>
            </View>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='AA' keyboardType='number-pad'
              onChangeText={ value => this.setState({ year: value }) }/>
            </View>
          </View>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._ageCalc}>
            <Text style={styles.buttonText}>CALCULAR EDAD</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.ageView}>
          <Text style={styles.ageTextPrimary}>Tu edad es:</Text>
          <Text style={styles.ageNumber}>{this.state.edad}</Text>
          <Text style={styles.ageTextSecondary}>Años</Text>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

export default App; // AgeInput
</code>```

Thanks for your help

答:
You can do something like this...

 render () {
 const { navigate } = props.navigation;
     //function to go to next screen
     goToNextScreen = () => {
         return navigate('Home');
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled enableOnAndroid={true}
      resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.topView}>
          // This is the button I press to go back to the first screen
          <TouchableOpacity style={styles.img} onPress={() => this.goToNextScreen()}>
            <Image source={flecha} />
          </TouchableOpacity>
          <View style={styles.topTextWrapper}>
            <Text style={styles.topTextPrimary}>Bienvenido a Neuron</Text>
              <Text style={styles.topTextSecondary}>¿O no?</Text>
            </View>
        </View>

        <View style={styles.middleView}>
          <Text style={styles.formText}>Fecha de nacimiento</Text>
          <View style={styles.formRow}>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='DD' keyboardType='number-pad'
              onChangeText={ value => this.setState({ day: value }) }/>
            </View>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='MM' keyboardType='number-pad'
              onChangeText={ value => this.setState({ month: value }) }/>
            </View>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='AA' keyboardType='number-pad'
              onChangeText={ value => this.setState({ year: value }) }/>
            </View>
          </View>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._ageCalc}>
            <Text style={styles.buttonText}>CALCULAR EDAD</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.ageView}>
          <Text style={styles.ageTextPrimary}>Tu edad es:</Text>
          <Text style={styles.ageNumber}>{this.state.edad}</Text>
          <Text style={styles.ageTextSecondary}>Años</Text>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

export default App; ```

Title: Navigating back to start screen

Body:
I have two different documents with two different screens. After an e-mail validation on the first screen, I'm now able to go to the second screen. However, I want to return to the first screen. None of the mentioned approaches on the React Navigation 5.x documentation works for me.

This is the code on the App.js:

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import firebase from './firebase';
import * as EmailValidator from 'email-validator';
import { HitTestResultTypes } from 'expo/build/AR';
import logo from './assets/Circulo.png';
import AgeInput from './AgeInput';

// Clase que representa el diseño de la pantalla inicial de la app
class HomeScreen extends Component {
  state = { username: null, password: null, nonValidInput: null }

  _onSubmit = ({ navigation }) =>{
    if(EmailValidator.validate(this.state.username) == true) {
      this.setState({ nonValidInput: false });
      const { username, password } = this.state;

      try {
        // THIS IS WHERE I GO TO THE SECOND SCREEN
        firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(() => this.props.navigation.navigate('Age'));
      } catch {
        Alert.alert(
          'Error',
          'Los datos no son correctos',
          [
            { text: 'Ok' }
          ],
          { cancelable: false }
        );
      }

    } else {
      this.setState({ nonValidInput: true });
    }
  }

  render() {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
      enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.logo}>
          <Image source = {logo} style={styles.img}/>
          <Text style={styles.textLogoPrimary}>Neuron App</Text>
          <Text style={styles.textLogoSecondary}>Test</Text>
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Correo Electrónico</Text>
          <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
          style={styles.formInput} />
          {this.state.nonValidInput ? (
            <Text style={styles.textAlert}>Correo electrónico no valido.</Text>
          ) : null}
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Contraseña</Text>
          <TextInput style={styles.formInput} placeholder='Contraseña' onChangeText={value => this.setState({ password: value })}
          secureTextEntry={true}/>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
            <Text style={styles.buttonText}>Iniciar</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

const Stack = createStackNavigator();

class App extends Component {
  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator screenOptions={{headerShown: false}} initialRouteName="Home">
          <Stack.Screen name='Home' component={HomeScreen} />
          <Stack.Screen name='Age' component={AgeInput} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}

and this is the code on the AgeInput.js

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Home from './App';

class App extends Component { // AgeInput
  state = { date: null, edad: null, day: null, month: null, year: null }

  _ageCalc = () => {
    if(this.state.day < 32 && this.state.day > 0 && this.state.month < 13 && this.state.month > 0 && this.state.year != 0) {
      var fecha = Date.parse(this.state.year + '-' + this.state.month + '-' + this.state.day);

      var hoy = new Date();
      var fechaNacimiento = new Date(fecha);
      var edad_ahora = hoy.getFullYear() - fechaNacimiento.getFullYear();
      var mes = hoy.getMonth() - fechaNacimiento.getMonth();

      if (mes < 0 || (mes === 0 && hoy.getDate() < fechaNacimiento.getDate())) {
        edad_ahora--;
      }

      this.setState({ edad: edad_ahora });
    } else {
      Alert.alert(
        'Error',
        'Por favor introduce una fecha valida',
        [
          { text: 'Ok' }
        ],
        { cancelable: false },
      );
    }
  }

  render () {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled enableOnAndroid={true}
      resetScrollToCoords={{x:0, y:0}}>
        <View style={styles.topView}>
          // This is the button I press to go back to the first screen
          <TouchableOpacity style={styles.img} onPress={() => this.props.navigator.navigate('Home')}>
            <Image source={flecha} />
          </TouchableOpacity>
          <View style={styles.topTextWrapper}>
            <Text style={styles.topTextPrimary}>Bienvenido a Neuron</Text>
              <Text style={styles.topTextSecondary}>¿O no?</Text>
            </View>
        </View>

        <View style={styles.middleView}>
          <Text style={styles.formText}>Fecha de nacimiento</Text>
          <View style={styles.formRow}>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='DD' keyboardType='number-pad'
              onChangeText={ value => this.setState({ day: value }) }/>
            </View>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='MM' keyboardType='number-pad'
              onChangeText={ value => this.setState({ month: value }) }/>
            </View>
            <View style={styles.textInputWrapper}>
              <TextInput style={styles.formInput} placeholder='AA' keyboardType='number-pad'
              onChangeText={ value => this.setState({ year: value }) }/>
            </View>
          </View>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._ageCalc}>
            <Text style={styles.buttonText}>CALCULAR EDAD</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.ageView}>
          <Text style={styles.ageTextPrimary}>Tu edad es:</Text>
          <Text style={styles.ageNumber}>{this.state.edad}</Text>
          <Text style={styles.ageTextSecondary}>Años</Text>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

export default App; // AgeInput

Thanks for your help


问:
Autodesk forge viewer update three js geometries scale
I have a basic viewer set up with a model that I am adding some spheres to. The actual adding of the spheres works fine.

```<code>var geometry = new THREE.SphereGeometry( 50, 50, 50 );
viewer.impl.createOverlayScene('TestOverlay' , material)
var cube = new THREE.Mesh(geometry, material)
viewer.impl.addOverlay('TestOverlay', cube);
</code>```

I am trying to get the added spheres to change size triggered by a button outside of the viewer by setting the scale.

```<code>scale.set(2, 2, 2)
</code>```

technically this works but the sphere will only change scale the next time the user interacts with the viewer in some way e.g. something as simple as the users mouse entering the viewer will cause it to update.

I have tried setting the needs update fields on the three js geometry object but that didnt change anything and I could not find anything in the forge documentation about manually updating it.

is there a way to force the update from Javascript

答:
Try trigger re-rendering when the scene needs updating to reflect the changes immediately with:</p>

```<code>viewer.impl.invalidate(needsClear, needsRender, overlayDirty) // e.g. viewer.impl.invalidate(true)

</code>```

Body:
I have a basic viewer set up with a model that I am adding some spheres to. The actual adding of the spheres works fine.

var geometry = new THREE.SphereGeometry( 50, 50, 50 );
viewer.impl.createOverlayScene('TestOverlay' , material)
var cube = new THREE.Mesh(geometry, material)
viewer.impl.addOverlay('TestOverlay', cube);

I am trying to get the added spheres to change size triggered by a button outside of the viewer by setting the scale.

scale.set(2, 2, 2)

technically this works but the sphere will only change scale the next time the user interacts with the viewer in some way e.g. something as simple as the users mouse entering the viewer will cause it to update.

I have tried setting the needs update fields on the three js geometry object but that didnt change anything and I could not find anything in the forge documentation about manually updating it.

is there a way to force the update from Javascript

Body:
Try trigger re-rendering when the scene needs updating to reflect the changes immediately with:

viewer.impl.invalidate(needsClear, needsRender, overlayDirty) // e.g. viewer.impl.invalidate(true)


问:
where is the tmp/setup folder created when doing ADD cmd in docker?
My dockerfile has this line, it sends the txt file to /tmp/setup folder, but i dont see it anywhere in the current docker folder where Dockerfile sits.

```<code>ADD requirements.txt /tmp/setup/requirements.txt
</code>```

how do i look inside this folder? where is "tmp/setup" located?

答:
This line(ADD requirements.txt /tmp/setup/requirements.txt) will copy the file requirements.txt from the current folder to the folder /tmp/setup in the filesystem of Docker image when you building your image.
You can find this file a folder in the container that run from the built image, not in the current Dockerfile folder.

Body:
My dockerfile has this line, it sends the txt file to /tmp/setup folder, but i dont see it anywhere in the current docker folder where Dockerfile sits.

ADD requirements.txt /tmp/setup/requirements.txt

how do i look inside this folder? where is "tmp/setup" located?


问:
Set classNames of React Transition Group with stage
I'm using React Transition Group. I have state classFade, and set classNames of React Transition Group = classFade. I want when I click to next button, classFade='fadeRight' and content will fade to the right. When I click to prev button, classFade='fadeLeft' and content will fade to the left. But react transition group takes the previous value, not the value after I pass it on. For example, when I clicked Next Button, it received my original classFade empty value, not 'fadeRight', only when click the next button again, will it succeed.

My stage:

```<code>const [items, setItems] = useState(
    { id: uuid(), text: 'Buy eggs', classFade: '' }
  );
</code>```

React Transition Group:

```<code><TransitionGroup>
  <CSSTransition
    key={items.id}
    timeout={500}
    classNames={items.classFade}
  >
    {items.text}
  </CSSTransition>
</TransitionGroup>
</code>```

Example when click next button:

```<code>    setItems({
      id: uuid(),
      text,
      classFade: 'fadeRight',
    });
</code>```

You can check full code and run demo here: https://codesandbox.io/s/transitiongroup-component-8x520

答:
My problem resolved in https://github.com/reactjs/react-transition-group/issues/182. They should be add this to docs -.- </p>

```<code>//This returns a childFactory to provide to TransitionGroup
const childFactoryCreator = (classNames) => (
  (child) => (
    React.cloneElement(child, {
      classNames
    })
  )
);

<TransitionGroup
  childFactory={childFactoryCreator(condition ? "anim1" : "anim2)}
>
  <CSSTransition
     key={key}
     classNames={condition ? "anim1" : "anim2"}
  >
     //Item that gets transitioned goes here
  </CSSTransition>
</TransitionGroup>
</code>```

Body:
I'm using React Transition Group. I have state classFade, and set classNames of React Transition Group = classFade. I want when I click to next button, classFade='fadeRight' and content will fade to the right. When I click to prev button, classFade='fadeLeft' and content will fade to the left. But react transition group takes the previous value, not the value after I pass it on. For example, when I clicked Next Button, it received my original classFade empty value, not 'fadeRight', only when click the next button again, will it succeed.

My stage:

const [items, setItems] = useState(
    { id: uuid(), text: 'Buy eggs', classFade: '' }
  );

React Transition Group:

<TransitionGroup>
  <CSSTransition
    key={items.id}
    timeout={500}
    classNames={items.classFade}
  >
    {items.text}
  </CSSTransition>
</TransitionGroup>

Example when click next button:

    setItems({
      id: uuid(),
      text,
      classFade: 'fadeRight',
    });

You can check full code and run demo here: https://codesandbox.io/s/transitiongroup-component-8x520

Body:
My problem resolved in https://github.com/reactjs/react-transition-group/issues/182. They should be add this to docs -.-

//This returns a childFactory to provide to TransitionGroup
const childFactoryCreator = (classNames) => (
  (child) => (
    React.cloneElement(child, {
      classNames
    })
  )
);

<TransitionGroup
  childFactory={childFactoryCreator(condition ? "anim1" : "anim2)}
>
  <CSSTransition
     key={key}
     classNames={condition ? "anim1" : "anim2"}
  >
     //Item that gets transitioned goes here
  </CSSTransition>
</TransitionGroup>


问:
Cordova CLI - not updating config.xml
I have used the Cordova CLI 6.5.0 for the past 1-2 years, and it's acted normally.  We are upgrading our main app to android@8.0.0, which required a Cordova CLI upgrade.  In using Cordova CLI 9.0.0, I'm noticing that many things are no longer updating the config.xml file:

platform adds - no longer see <engine> elements

plugin adds - not adding <plugin> elements

I am making sure --save is used in the commands (which I gather is not even required anymore).  When I run a cordova platform list or cordova plugin list I see the expected platforms/plugins.  I also see that the package.json is used more heavily now.  However, the plugin/platform versions are not in the package.json so I can't imagine that's a complete replacement?

Lastly, some additional things I've tried:

running cordova platform android save

running cordova clean and cordova prepare

adding and removing the platform (and ditching the related directories)

Running an actual build (which works fine)

Is this "normal"?  Do these newer cordova versions not leverage the config.xml as regularly now?

答:
Cordova 9.0.0</p>

```<code>cordova plugin add cordova-plugin-device
cordova plugin save
</code>```

Title: Cordova CLI - not updating config.xml

Body:
Cordova 9.0.0

cordova plugin add cordova-plugin-device
cordova plugin save


问:
Kerberos service started with Error: Cannot open DB2 database on Ubuntu 18
I installed kerberos on Ubuntu 18 with sudo apt install krb5-kdc krb5-admin-server

But, When I ran systemctl status krb5-kdc.service, it turns out:

```<code>Feb 17 21:25:23 device2 krb5kdc[8675]: Cannot open DB2 database '/var/lib/krb5kdc/principal': No such file or directory - while initializing database for realm DENNIS.COM
Feb 17 21:25:23 device2 krb5kdc[8675]: krb5kdc: cannot initialize realm DENNIS.COM - see log file for details
Feb 17 21:25:23 device2 systemd[1]: krb5-kdc.service: Control process exited, code=exited status=1
Feb 17 21:25:23 device2 systemd[1]: krb5-kdc.service: Failed with result 'exit-code'.
Feb 17 21:25:23 device2 systemd[1]: Failed to start Kerberos 5 Key Distribution Center.
</code>```

I have set the realm with kdb5_util create -r DENNIS.COM -s

```<code>[realms]
    DENNIS.COM = {
        kdc = device2
        admin_server = device2
    }
</code>```

答:
solved the problem with the following steps:</p>

```<code>1. sudo kdb5_util create -r DENNIS.COM -s
2. set a password.
3. check if there is /var/lib/krb5kdc/principal existed.
4. Then sudo service krb5-kdc restart.
</code>```

Body:
I installed kerberos on Ubuntu 18 with sudo apt install krb5-kdc krb5-admin-server

But, When I ran systemctl status krb5-kdc.service, it turns out:

Feb 17 21:25:23 device2 krb5kdc[8675]: Cannot open DB2 database '/var/lib/krb5kdc/principal': No such file or directory - while initializing database for realm DENNIS.COM
Feb 17 21:25:23 device2 krb5kdc[8675]: krb5kdc: cannot initialize realm DENNIS.COM - see log file for details
Feb 17 21:25:23 device2 systemd[1]: krb5-kdc.service: Control process exited, code=exited status=1
Feb 17 21:25:23 device2 systemd[1]: krb5-kdc.service: Failed with result 'exit-code'.
Feb 17 21:25:23 device2 systemd[1]: Failed to start Kerberos 5 Key Distribution Center.

I have set the realm with kdb5_util create -r DENNIS.COM -s

[realms]
    DENNIS.COM = {
        kdc = device2
        admin_server = device2
    }

Body:
solved the problem with the following steps:

1. sudo kdb5_util create -r DENNIS.COM -s
2. set a password.
3. check if there is /var/lib/krb5kdc/principal existed.
4. Then sudo service krb5-kdc restart.