问:
How do I see if a annotation is selected with MapBox in SwiftUI?
I'm trying to update my UI accordingly when a MapBox annotation is selected using swiftUI. Everything works good until I change the bool within the MapView Coordinator. Once I do, the annotations will not update.

```<code>struct MainView: View {

@State var annotations: [MGLPointAnnotation] = []
@State var pingDetailsShown = false

    var body: some View {

        ///...

        MapView(annotations: self.$annotations, pingDetailsShown: self.$pingDetailsShown).centerCoordinate(.init(latitude: 53.460067, longitude: -114.996973)).zoomLevel(5.0)
//...
</code>```

MapView

```<code>struct MapView: UIViewRepresentable {

@Binding var annotations: [MGLPointAnnotation]
@Binding var pingDetailsShown: Bool

private let mapView: MGLMapView = MGLMapView(frame: .zero, styleURL: MGLStyle.streetsStyleURL)

func makeUIView(context: UIViewRepresentableContext<MapView>) -> MGLMapView {
    mapView.delegate = context.coordinator
    return mapView
}

func updateUIView(_ uiView: MGLMapView, context: UIViewRepresentableContext<MapView>) {
    updateAnnotations()

}

func makeCoordinator() -> MapView.Coordinator {
    Coordinator(self, pingDetailsShown: $pingDetailsShown)
}

private func updateAnnotations() {
    if let currentAnnotations = mapView.annotations {
        mapView.removeAnnotations(currentAnnotations)
    }
    mapView.addAnnotations(annotations)
}
</code>```

Here's where I run into trouble...

```<code>final class Coordinator: NSObject, MGLMapViewDelegate {
    var control: MapView
    var startZoom: Double = 5.0
    @Binding var pingDetailsShown: Bool

    init(_ control: MapView, pingDetailsShown: Binding<Bool>) {
        self.control = control
        self._pingDetailsShown = pingDetailsShown
    }

    func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
        print(((annotation.title ?? "") ?? ""))

        pingDetailsShown = true
    }

    func mapView(_ mapView: MGLMapView, didDeselect annotationView: MGLAnnotationView) {

            pingDetailsShown = false

        }
}
</code>```

I've tried the pingDetailsShown as not binded also, but the same issue happens, as soon as I change the pingDetailsShown value, it no longer allows the MapView annotations to be updated.

All I am trying to do is update the MainView UI when an annotation is selected, and have the annotations still refresh after.

答:
You should change updateUIView and updateAnnotations to include the current view being refreshed:</p>

```<code>func updateUIView(_ uiView: MGLMapView, context: Context) {
    updateAnnotations(uiView)
}

private func updateAnnotations(_ view: MGLMapView) {
    if let currentAnnotations = view.annotations {
        view.removeAnnotations(currentAnnotations)
    }
    view.addAnnotations(annotations)
}
</code>```

Body:
I'm trying to update my UI accordingly when a MapBox annotation is selected using swiftUI. Everything works good until I change the bool within the MapView Coordinator. Once I do, the annotations will not update.

struct MainView: View {

@State var annotations: [MGLPointAnnotation] = []
@State var pingDetailsShown = false

    var body: some View {

        ///...

        MapView(annotations: self.$annotations, pingDetailsShown: self.$pingDetailsShown).centerCoordinate(.init(latitude: 53.460067, longitude: -114.996973)).zoomLevel(5.0)
//...

MapView

struct MapView: UIViewRepresentable {

@Binding var annotations: [MGLPointAnnotation]
@Binding var pingDetailsShown: Bool

private let mapView: MGLMapView = MGLMapView(frame: .zero, styleURL: MGLStyle.streetsStyleURL)

func makeUIView(context: UIViewRepresentableContext<MapView>) -> MGLMapView {
    mapView.delegate = context.coordinator
    return mapView
}

func updateUIView(_ uiView: MGLMapView, context: UIViewRepresentableContext<MapView>) {
    updateAnnotations()

}

func makeCoordinator() -> MapView.Coordinator {
    Coordinator(self, pingDetailsShown: $pingDetailsShown)
}

private func updateAnnotations() {
    if let currentAnnotations = mapView.annotations {
        mapView.removeAnnotations(currentAnnotations)
    }
    mapView.addAnnotations(annotations)
}

Here's where I run into trouble...

final class Coordinator: NSObject, MGLMapViewDelegate {
    var control: MapView
    var startZoom: Double = 5.0
    @Binding var pingDetailsShown: Bool

    init(_ control: MapView, pingDetailsShown: Binding<Bool>) {
        self.control = control
        self._pingDetailsShown = pingDetailsShown
    }

    func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
        print(((annotation.title ?? "") ?? ""))

        pingDetailsShown = true
    }

    func mapView(_ mapView: MGLMapView, didDeselect annotationView: MGLAnnotationView) {

            pingDetailsShown = false

        }
}

I've tried the pingDetailsShown as not binded also, but the same issue happens, as soon as I change the pingDetailsShown value, it no longer allows the MapView annotations to be updated.

All I am trying to do is update the MainView UI when an annotation is selected, and have the annotations still refresh after.

Body:
You should change updateUIView and updateAnnotations to include the current view being refreshed:

func updateUIView(_ uiView: MGLMapView, context: Context) {
    updateAnnotations(uiView)
}

private func updateAnnotations(_ view: MGLMapView) {
    if let currentAnnotations = view.annotations {
        view.removeAnnotations(currentAnnotations)
    }
    view.addAnnotations(annotations)
}


来源: stackexchange

问:
Javascript required attribute not working with e.preventDefault
I have a form with inputs that have the required attribute.However, I dont want the form to be submitted normally, but it uses ajax.Thus, I set the form action to javascript:void(0) .But doing so, renders the required attribute useless.It doesn't work

How can I fix that?

This is my form

```<code><form action="javascript:void(0)"> <input name="email" required> </form>`
</code>```

答:
So use the submit handler on the form and cancel the default action.

document.querySelector("#myForm").addEventListener("submit", function (evt) {
  evt.preventDefault();
  // do you ajax submission here
  console.log('submitted')
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="myForm">
  <label for="email">email:</label> <input id="email" name="email" type="email" required>
  <button>Submit</button>
</form></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a form with inputs that have the required attribute.However, I dont want the form to be submitted normally, but it uses ajax.Thus, I set the form action to javascript:void(0) .But doing so, renders the required attribute useless.It doesn't work

How can I fix that?

This is my form

<form action="javascript:void(0)"> <input name="email" required> </form>`

Body:
So use the submit handler on the form and cancel the default action.

document.querySelector("#myForm").addEventListener("submit", function (evt) {
  evt.preventDefault();
  // do you ajax submission here
  console.log('submitted')
})

<form id="myForm">
  <label for="email">email:</label> <input id="email" name="email" type="email" required>
  <button>Submit</button>
</form>


问:
Puppet not handling squared brackets in the source attribute for file resource
I am still facing this issue, when trying to copy git installation files by copying a folder and making it recursive. There is a file called [.exe and it is failing with:

Error: /Stage[main]/Tcagents/File[Copy Team City agent tools]: Failed to generate additional resources using 'eval_generate': Parameter source failed on File[D:/TeamCityTools/git-2.5.0/usr/bin/[.exe]: Could not understand source puppet:///tools/TeamCityTools/git-2.5.0/usr/bin/[.exe: bad URI(is not URI?): puppet:///tools/TeamCityTools/git-2.5.0/usr/bin/[.exe`

While reading other requests, I saw that is is due to the URI library Puppet uses for validating the path. I also found the same issue in https://tickets.puppetlabs.com/browse/PUP-3135 but it is accepted without a solution.

I wonder if there is a workaround you recommend or a fix for this. Using Puppet 4.4.2.

Resource is:

```<code>file{'Copy Team City agent tools':
    ensure => directory,
    path => $tc_tools_path,
    source => 'puppet:///tools/TeamCityTools',
    recurse => true,
}
</code>```

答: Puppet has not still resolved this (https://tickets.puppetlabs.com/browse/PUP-3135).</p>

ContentLicense: CC BY-SA 3.0

Body:
I am still facing this issue, when trying to copy git installation files by copying a folder and making it recursive. There is a file called [.exe and it is failing with:

Error: /Stage[main]/Tcagents/File[Copy Team City agent tools]: Failed to generate additional resources using 'eval_generate': Parameter source failed on File[D:/TeamCityTools/git-2.5.0/usr/bin/[.exe]: Could not understand source puppet:///tools/TeamCityTools/git-2.5.0/usr/bin/[.exe: bad URI(is not URI?): puppet:///tools/TeamCityTools/git-2.5.0/usr/bin/[.exe`

While reading other requests, I saw that is is due to the URI library Puppet uses for validating the path. I also found the same issue in https://tickets.puppetlabs.com/browse/PUP-3135 but it is accepted without a solution.

I wonder if there is a workaround you recommend or a fix for this. Using Puppet 4.4.2.

Resource is:

file{'Copy Team City agent tools':
    ensure => directory,
    path => $tc_tools_path,
    source => 'puppet:///tools/TeamCityTools',
    recurse => true,
}


问:
iterate an actively used database table in cron jobs without missing any row
How would you correctly iterate all the rows of a database query when doing multiple passes of a long operation without missing any row? In my case i have alphanumeric IDs, so id column is not reliable...

The main problem is that the query results may change between each cron task execution.

A first idea could be to store the offset / "number of rows processed". But if one of the already processed rows is deleted the others would shift and the first one would be skipped.

If I store the id of the last processed row and skip to the one after it I have a worse problem: if that exact row is deleted the next cron job will skip every remaining row.

Is there any more "standard" way of iterating a table like this ?

I'm doing this in php with a third party orm engine using sql as data store, but i think it's more a general question so anyone feel free to retag  this more appropriately.

答: Well you can use DB transactions to resolve concurrency if any 2 crons hit simultaneously. To know from which row to start next, you can have an extra column in DB say processed which stores some integer say 1.  So your next cron hit will fetch rows that don't have 1 in the processed column.


问:
How to get value from dictionary by key and compare that value with zero c#?
I have dictionary, and I want to threw exception, if value(not key) is < 0.
But i am don't know how to check this condition.
Help me please</p>

```<code>public Dictionary<string, double> Components = new Dictionary<string, double>();

if (/*Components key amount < 0*/)
 {
   throw new Exception("Value can't be smaller then 0!");
 }
</code>```

答:
Just get the value for a given key and check what the value is:</p>

```<code>double value;
if (Components.TryGetValue(key, out value) && value < 0)
{
    throw new Exception("Value can't be smaller then 0!");
}
</code>```

Body:
I have dictionary, and I want to threw exception, if value(not key) is < 0.
But i am don't know how to check this condition.
Help me please

public Dictionary<string, double> Components = new Dictionary<string, double>();

if (/*Components key amount < 0*/)
 {
   throw new Exception("Value can't be smaller then 0!");
 }

Body:
Just get the value for a given key and check what the value is:

double value;
if (Components.TryGetValue(key, out value) && value < 0)
{
    throw new Exception("Value can't be smaller then 0!");
}


问:
Unable to select text field with javascript
I must be missing something basic. I can't give the textfield focus with the following:

 <input id="hi"></input>

```

答:
Try this in Script:

document.getElementById("hi").innerHTML


问:
How to run scripts simultaneously with Puppeteer/Javascript?
I am using puppeteer to do some testing.

No code written because I don't even know how to approach this.

```<code>• I have a list of 10 IDs inside an array

• For each ID -  a new page/tab is opened

• I want to run the script for each page/ tab without having to wait for the previous page/tab
to finish before starting the next. Hence the simultaneous execution.
</code>```

So 10 pages will be running the same script at the same time?

Is this possible with Javascript and puppeteer?

答:
Yes, it's default asynchronous behavior. You just need to open 10 tabs and run your script over these pages. </p>

<p>Here is the sample: </p>

```<code>(async () => {
    const browser = await puppeteer.launch({
        headless: false
    });
    const ids = ['1', '2', '3'];
    const pool = [];

    for (let index = 0; index < ids.length; index++) {
        pool.push(
            browser.newPage() // create new page for each id
                .then(page => {
                    const currentId = ids[index];
                    // your script over current page
                })
        );
    }

    await Promise.all(pool); // wait until all 10 pages finished
    await browser.close(); // close the browser
})();
</code>```

Body:
I am using puppeteer to do some testing.

No code written because I don't even know how to approach this.

• I have a list of 10 IDs inside an array

• For each ID -  a new page/tab is opened

• I want to run the script for each page/ tab without having to wait for the previous page/tab
to finish before starting the next. Hence the simultaneous execution.

So 10 pages will be running the same script at the same time?

Is this possible with Javascript and puppeteer?

Body:
Yes, it's default asynchronous behavior. You just need to open 10 tabs and run your script over these pages.

Here is the sample:

(async () => {
    const browser = await puppeteer.launch({
        headless: false
    });
    const ids = ['1', '2', '3'];
    const pool = [];

    for (let index = 0; index < ids.length; index++) {
        pool.push(
            browser.newPage() // create new page for each id
                .then(page => {
                    const currentId = ids[index];
                    // your script over current page
                })
        );
    }

    await Promise.all(pool); // wait until all 10 pages finished
    await browser.close(); // close the browser
})();


问:
How to close modal on hardware back button in ionic app?
I'm using Ionic 5 in my pwa application (angular framework), and I want to close the opening modal/popover (if exist) when the user uses the hardware back button..

I couldn't find any solution online that works on ionic 4+ pwa applications.

Any help will be appreciated.

答:
You can add a handler for the backbutton.

Cordova:
Inject Platform in a constructor and

```<code>this.platform.backButton.subscribe(() => {
  // close modal here
});
</code>```

Capacitor:

```<code>import { Plugins, AppState } from '@capacitor/core';
const { App } = Plugins;
App.addListener('backButton', () => {
  // close modal here
});
</code>```

Body:
You can add a handler for the backbutton.

Cordova:
Inject Platform in a constructor and

this.platform.backButton.subscribe(() => {
  // close modal here
});

Capacitor:

import { Plugins, AppState } from '@capacitor/core';
const { App } = Plugins;
App.addListener('backButton', () => {
  // close modal here
});


问:
Java to HTML Parser / State Machine
I wish to create a app that translates input java code into HTML formatted java code,

For example:

```<code>public class ReadWithScanner
</code>```

Would become

```<code><span class="public">public</span> <span class="class">class</span> ReadWithScanner
</code>```

However it gets quite complicated when it comes to parameters and regular expressions. Now I have a bit of time on my hands, and I wish to write my own code parser.

How would I start this? and is there any tutorials or online content to not only help me write this, but understand it.

Thanks

答:
I think you need a lexical analyzer.
I used early the Flex lexical analyzer. It is not too complicated to use.
If you need to parse the analyzed text you can use the bison c++
bisoncpp.sourceforge.net/
(C++ konwledge need and linux environment)</p>

Title: Java to HTML Parser / State Machine

Body:
I wish to create a app that translates input java code into HTML formatted java code,

For example:

public class ReadWithScanner

Would become

public class ReadWithScanner

However it gets quite complicated when it comes to parameters and regular expressions. Now I have a bit of time on my hands, and I wish to write my own code parser.

How would I start this? and is there any tutorials or online content to not only help me write this, but understand it.

Thanks


问:
Creating an efficient indexer for my Azure Search Service
My data source cannot be a single table as I need data that spans across 6 tables. For that I have created a view that does joins on these tables.
When I use this view as data source, indexing takes a lot of times and times out. I tried increasing timeout to 40 minutes  and one more suggested change:

"disableOrderByHighWaterMarkColumn" : true

It timed-out. I also set Batch Size:1000. This time it  populated the index but failed after few hours saying "connection lost". and "thanks" to disableOrderByHighWaterMarkColumn, If I rerun indexer again it will process all the rows again.

My question is what is the best way to approach a solution to this problem.

Follow-up Question: Since I am relying on a view, I cannot have auto change tracking. I am using a high watermark column (LastUpdatedTime) to track changes in my View. I only want to keep 6 months of data in my index so I am not sure how I can do that when I am using View. I have "where CreateDateTime > dateadd(month, -6, getdate())" clause already in my View but this will not enable Indexer to delete "out-of-time-window" rows(documents) from index. How can I achieve my goals here?
Should I write a processor task to periodically query all documents using C# SDK and delete documents based on date?

答:
Sorry to hear the Azure SQL Database indexer is giving you trouble. I noticed a couple of things in your question that might be worth thinking about in terms of SQL performance:

My data source cannot be a single table as I need data that spans across 6 tables. For that I have created a view that does joins on these tables When I use this view as data source, indexing takes a lot of times and times out.

It's worth taking a look at the query performance troubleshooting guide and figure out what exactly is happening in your Azure SQL database that is causing problems. Assuming you want to use change tracking support, the default query the indexer uses against the SQL database looks like this:
SELECT * FROM c WHERE hwm_column > @hwmvalue ORDER BY hwm_column
We frequently see issues with performance here when there isn't an index on the hwm_column or if hwm_column is computed. You can read more about issues with the high water mark column here.

I tried increasing timeout to 40 minutes and one more suggested change: "disableOrderByHighWaterMarkColumn" : true It timed-out. I also set Batch Size:1000. This time it populated the index but failed after few hours saying "connection lost". and "thanks" to disableOrderByHighWaterMarkColumn, If I rerun indexer again it will process all the rows again.

disableOrderByHighWaterMarkColumn doesn't seem like it will work for your scenario, so I agree that you shouldn't set it. Decreasing the batch size seems to have had a positive effect, I would consider measuring the performance gain here using the troubleshooting guide referenced above

Follow-up Question: Since I am relying on a view, I cannot have auto change tracking. I am using a high watermark column (LastUpdatedTime) to track changes in my View. I only want to keep 6 months of data in my index so I am not sure how I can do that when I am using View. I have "where CreateDateTime > dateadd(month, -6, getdate())" clause already in my View but this will not enable Indexer to delete "out-of-time-window" rows(documents) from index. How can I achieve my goals here? Should I write a processor task to periodically query all documents using C# SDK and delete documents based on date?

Instead of filtering out data that is more than 6 months old, I would consider adding soft delete policy. The challenge here is that the indexer needs to pick up rows that should be deleted. The easiest way to accomplish this might updating your application logic to add a new column to your view indicating the row should be deleted. Once the value of this column changes, the LastUpdatedTime should also be updated so it shows up in the next indexer query.
You can write your own processor task, but querying all documents in Azure Cognitive Search and paging through them may have negative performance implications on your search performance. I would recommend trying to get it working with your indexer first.


问:
Reset scroll inside modal
I'm facing a huge problem. I have a modal that renders a list of texts. The div where the text is shown has a scrollbar, but when I change the text the scrollbar remains at the same spot. If I scroll to the middle and change the text it will appear from the middle and not from the top as it should.
I've tried this code: window.scrollTo(0,0) but it resets the main page scroll not the modal one.

Could anyone help me?

答:
I'm not sure I'm understanding your question. It is more helpful if you post the bit of code that's giving you trouble so we can clearly see what's going wrong. That said, window.scrollTo(0,0) will scroll the whole page. If you want to scroll to the top of an element like that, call .scrollTop from the element you wish to scroll. I think you are looking for something like this:</p>

```<code>$("#myScrollDiv").scrollTop(0);
</code>```

Title: Reset scroll inside modal

Body:
I'm not sure I'm understanding your question. It is more helpful if you post the bit of code that's giving you trouble so we can clearly see what's going wrong. That said, window.scrollTo(0,0) will scroll the whole page. If you want to scroll to the top of an element like that, call .scrollTop from the element you wish to scroll. I think you are looking for something like this:

$("#myScrollDiv").scrollTop(0);


问:
How to cancel BackgroundWorker in WPF without DoEvents
I have a search box that works great in WinForms, but is giving me trouble in WPF.

It works by starting a search each time a letter is pushed, similar to Google.

```<code>    If (txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter) Then
        If SearchWorker.IsBusy Then
            SearchWorker.CancelAsync()
            Do While SearchWorker.IsBusy
                'Application.DoEvents()
                'System.Threading.Thread.Sleep(500)
            Loop
        End If
        doSearchText = txtQuickSearch.Text
        SearchWorker.RunWorkerAsync()
    End If
</code>```

Every time a key is pushed it cancels the current searchWorker then restarts it. In WinForms the Do while searchworker.isbusy doevents loop worked great, but since I don't have access to that anymore, I need to figure out a better way to do it. Sleep() deadlocks it, and I've tried just doing i+=1 as a way to pass time until it's not busy, but that doesn't work either...

What should I do?

Update: Here's what I changed it to. It works, but the cancel part doesn't seem to ever trigger, this doesn't seem to be running async...

```<code>Imports System.ComponentModel
Imports System.Collections.ObjectModel
Imports System.Threading
Imports System.Threading.Tasks

Public Class QuickSearch
    Private doSearchText As String
    Private canceled As Boolean
    Private curSearch As String
    Dim searchResults As New ObservableCollection(Of ocSearchResults)

    'Task Factory
    Private cts As CancellationTokenSource
    Private searchtask As Task(Of ObservableCollection(Of ocSearchResults))

    Private Sub txtQuickSearch_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles txtQuickSearch.KeyDown
        If e.Key = Key.Enter Then
            curSearch = ""
        End If
        If ((txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter)) And Not txtQuickSearch.Text = curSearch Then
            If Not cts Is Nothing Then
                cts.Cancel()
                ColorChecker.CancelAsync()
                Try
                    ' searchtask.Wait()
                Catch ex As AggregateException
                    MsgBox(ex.InnerException.Message)
                End Try
                cts = New CancellationTokenSource
            Else
                cts = New CancellationTokenSource
            End If
            Dim cToken = cts.Token
            Me.Height = 400
            doSearchText = txtQuickSearch.Text
'This always completes fully before continuing on to tRunWorkerComplete(searchtask.Result) '
            searchtask = Task(Of ObservableCollection(Of ocSearchResults)).Factory.StartNew(Function() tPerformSearch(cToken), cToken)
            Try
                tRunWorkerCompleted(searchtask.Result)
            Catch ex As AggregateException
                ' MsgBox(ex.InnerException.Message)
            End Try
        Else
            If Not cts Is Nothing Then
                cts.Cancel()
            End If
            searchResults.Clear()
        End If
    End Sub

    Function tPerformSearch(ByVal ct As CancellationToken) As ObservableCollection(Of ocSearchResults)
        On Error GoTo sError

        canceled = False
        If curSearch = doSearchText Then
            canceled = True
            Return Nothing
        End If
        curSearch = doSearchText
        Dim SR As New ObservableCollection(Of ocSearchResults)

        Dim t As ocSearchResults
        Dim rSelect As New ADODB.Recordset
        Dim sSql As String = "SELECT DISTINCT CustomerID, CustomerName, City, State, Zip FROM qrySearchFieldsQuick WHERE "
        Dim sWhere As String = "CustomerName Like '" & doSearchText & "%'"

        SR.Clear()

        With rSelect
            .Open(sSql & sWhere & " ORDER BY CustomerName", MyCn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly)
            Do While Not .EOF
                If ct.IsCancellationRequested Then ' This never shows true, the process always returns a value, as if it wasn't async'
                    canceled = True
                    Return Nothing
                End If

                Do While IsDBNull(.Fields("CustomerID").Value)
                    .MoveNext()
                Loop

                t = New ocSearchResults(.Fields!CustomerID.Value, .Fields!CustomerName.Value.ToString.Trim, .Fields!City.Value.ToString.Trim, .Fields!State.Value.ToString.Trim, .Fields!Zip.Value.ToString.Trim)
                If Not SR.Contains(t) Then
                    SR.Add(t)
                End If
aMoveNext:
                .MoveNext()
            Loop
            .Close()
        End With

        Return SR
        Exit Function
sError:
        MsgBox(ErrorToString, MsgBoxStyle.Exclamation)
    End Function

    Sub tRunWorkerCompleted(ByVal SR As ObservableCollection(Of ocSearchResults))
        If canceled Then
            Exit Sub
        End If
        If cts.IsCancellationRequested Then
            Exit Sub
        End If

        searchResults.Clear()
        For Each t As ocSearchResults In SR
            searchResults.Add(t)
        Next

        ColorChecker = New BackgroundWorker
        ColorChecker.WorkerReportsProgress = True
        ColorChecker.WorkerSupportsCancellation = True
        ColorChecker.RunWorkerAsync(searchResults)

        lblRecordCount.Text = "(" & searchResults.Count & ") Records"

        progBar.Value = 100
        Exit Sub
sError:
        MsgBox(ErrorToString)
    End Sub
</code>```

答:
I am not sure a BackgroundWorker is flexible enough to provide an elegant solution for this type of background processing anyway. I think what I would do is to create a single dedicated thread for doing the searching. This thread would use the producer-consumer pattern for accepting work items and processing them.

The following code is a rough sketch of how I see this strategy working. You would call the SearchAsync method to request a new search. That method accepts a callback that gets invoked when and if the search operation found something. Notice that the consumer code (in the Run method) cancels its current search operation if another search request is queued. The effect is that the consumer only ever processes the latest request.

```<code>Public Class Searcher

  Private m_Queue As BlockingCollection(Of WorkItem) = New BlockingCollection(Of WorkItem)()

  Public Sub New()
    Dim t = New Thread(AddressOf Run)
    t.IsBackground = True
    t.Start()
  End Sub

  Public Sub SearchAsync(ByVal text As String, ByVal callback As Action)
    Dim wi = New WorkItem()
    wi.Text = text
    wi.Callback = callback
    m_Queue.Add(wi)
  End Sub

  Private Sub Run()
    Do While True
      Dim wi As WorkItem = m_Queue.Take()
      Dim found As Boolean = False
      Do While Not found AndAlso m_Queue.Count = 0
        ' Continue searching using your custom algorithm here.
      Loop
      If found Then
        wi.Callback()
      End If
    Loop
  End Sub

  Private Class WorkItem
    Public Text As String
    Public Callback As Action
  End Class

End Class
</code>```

Here is where the elegance happens. Look at how you can implement the logic from the UI thread now.

```<code>If (txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter) Then
    searcher.SearchAsync(txtQuickSearch.Text, AddressOf OnSearchComplete)
End If
</code>```

Note that OnSearchComplete will be executed on the worker thread so you will need to call Dispatcher.Invoke from within the callback if you want to publish the results to a UI control.

Body:
I have a search box that works great in WinForms, but is giving me trouble in WPF.

It works by starting a search each time a letter is pushed, similar to Google.

    If (txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter) Then
        If SearchWorker.IsBusy Then
            SearchWorker.CancelAsync()
            Do While SearchWorker.IsBusy
                'Application.DoEvents()
                'System.Threading.Thread.Sleep(500)
            Loop
        End If
        doSearchText = txtQuickSearch.Text
        SearchWorker.RunWorkerAsync()
    End If

Every time a key is pushed it cancels the current searchWorker then restarts it. In WinForms the Do while searchworker.isbusy doevents loop worked great, but since I don't have access to that anymore, I need to figure out a better way to do it. Sleep() deadlocks it, and I've tried just doing i+=1 as a way to pass time until it's not busy, but that doesn't work either...

What should I do?

Update: Here's what I changed it to. It works, but the cancel part doesn't seem to ever trigger, this doesn't seem to be running async...

Imports System.ComponentModel
Imports System.Collections.ObjectModel
Imports System.Threading
Imports System.Threading.Tasks

Public Class QuickSearch
    Private doSearchText As String
    Private canceled As Boolean
    Private curSearch As String
    Dim searchResults As New ObservableCollection(Of ocSearchResults)

    'Task Factory
    Private cts As CancellationTokenSource
    Private searchtask As Task(Of ObservableCollection(Of ocSearchResults))

    Private Sub txtQuickSearch_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles txtQuickSearch.KeyDown
        If e.Key = Key.Enter Then
            curSearch = ""
        End If
        If ((txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter)) And Not txtQuickSearch.Text = curSearch Then
            If Not cts Is Nothing Then
                cts.Cancel()
                ColorChecker.CancelAsync()
                Try
                    ' searchtask.Wait()
                Catch ex As AggregateException
                    MsgBox(ex.InnerException.Message)
                End Try
                cts = New CancellationTokenSource
            Else
                cts = New CancellationTokenSource
            End If
            Dim cToken = cts.Token
            Me.Height = 400
            doSearchText = txtQuickSearch.Text
'This always completes fully before continuing on to tRunWorkerComplete(searchtask.Result) '
            searchtask = Task(Of ObservableCollection(Of ocSearchResults)).Factory.StartNew(Function() tPerformSearch(cToken), cToken)
            Try
                tRunWorkerCompleted(searchtask.Result)
            Catch ex As AggregateException
                ' MsgBox(ex.InnerException.Message)
            End Try
        Else
            If Not cts Is Nothing Then
                cts.Cancel()
            End If
            searchResults.Clear()
        End If
    End Sub

    Function tPerformSearch(ByVal ct As CancellationToken) As ObservableCollection(Of ocSearchResults)
        On Error GoTo sError

        canceled = False
        If curSearch = doSearchText Then
            canceled = True
            Return Nothing
        End If
        curSearch = doSearchText
        Dim SR As New ObservableCollection(Of ocSearchResults)

        Dim t As ocSearchResults
        Dim rSelect As New ADODB.Recordset
        Dim sSql As String = "SELECT DISTINCT CustomerID, CustomerName, City, State, Zip FROM qrySearchFieldsQuick WHERE "
        Dim sWhere As String = "CustomerName Like '" & doSearchText & "%'"

        SR.Clear()

        With rSelect
            .Open(sSql & sWhere & " ORDER BY CustomerName", MyCn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly)
            Do While Not .EOF
                If ct.IsCancellationRequested Then ' This never shows true, the process always returns a value, as if it wasn't async'
                    canceled = True
                    Return Nothing
                End If

                Do While IsDBNull(.Fields("CustomerID").Value)
                    .MoveNext()
                Loop

                t = New ocSearchResults(.Fields!CustomerID.Value, .Fields!CustomerName.Value.ToString.Trim, .Fields!City.Value.ToString.Trim, .Fields!State.Value.ToString.Trim, .Fields!Zip.Value.ToString.Trim)
                If Not SR.Contains(t) Then
                    SR.Add(t)
                End If
aMoveNext:
                .MoveNext()
            Loop
            .Close()
        End With

        Return SR
        Exit Function
sError:
        MsgBox(ErrorToString, MsgBoxStyle.Exclamation)
    End Function

    Sub tRunWorkerCompleted(ByVal SR As ObservableCollection(Of ocSearchResults))
        If canceled Then
            Exit Sub
        End If
        If cts.IsCancellationRequested Then
            Exit Sub
        End If

        searchResults.Clear()
        For Each t As ocSearchResults In SR
            searchResults.Add(t)
        Next

        ColorChecker = New BackgroundWorker
        ColorChecker.WorkerReportsProgress = True
        ColorChecker.WorkerSupportsCancellation = True
        ColorChecker.RunWorkerAsync(searchResults)

        lblRecordCount.Text = "(" & searchResults.Count & ") Records"

        progBar.Value = 100
        Exit Sub
sError:
        MsgBox(ErrorToString)
    End Sub

Body:
I am not sure a BackgroundWorker is flexible enough to provide an elegant solution for this type of background processing anyway. I think what I would do is to create a single dedicated thread for doing the searching. This thread would use the producer-consumer pattern for accepting work items and processing them.

The following code is a rough sketch of how I see this strategy working. You would call the SearchAsync method to request a new search. That method accepts a callback that gets invoked when and if the search operation found something. Notice that the consumer code (in the Run method) cancels its current search operation if another search request is queued. The effect is that the consumer only ever processes the latest request.

Public Class Searcher

  Private m_Queue As BlockingCollection(Of WorkItem) = New BlockingCollection(Of WorkItem)()

  Public Sub New()
    Dim t = New Thread(AddressOf Run)
    t.IsBackground = True
    t.Start()
  End Sub

  Public Sub SearchAsync(ByVal text As String, ByVal callback As Action)
    Dim wi = New WorkItem()
    wi.Text = text
    wi.Callback = callback
    m_Queue.Add(wi)
  End Sub

  Private Sub Run()
    Do While True
      Dim wi As WorkItem = m_Queue.Take()
      Dim found As Boolean = False
      Do While Not found AndAlso m_Queue.Count = 0
        ' Continue searching using your custom algorithm here.
      Loop
      If found Then
        wi.Callback()
      End If
    Loop
  End Sub

  Private Class WorkItem
    Public Text As String
    Public Callback As Action
  End Class

End Class

Here is where the elegance happens. Look at how you can implement the logic from the UI thread now.

If (txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter) Then
    searcher.SearchAsync(txtQuickSearch.Text, AddressOf OnSearchComplete)
End If

Note that OnSearchComplete will be executed on the worker thread so you will need to call Dispatcher.Invoke from within the callback if you want to publish the results to a UI control.


问:
Is Dagger AppComponent available even after app get killed
I just started using Dagger library. I've created an AppComponent where I hold a singleton instance of my room database. I have a foreground service which needs to write something to room database when its notification button is clicked. As you know foreground service notification is always visible to user even if the user closes app and I thought if my app gets killed, the AppComponent will no longer be usable. But now I can access it and get the database instance when service notification button is clicked, even if my app has been cleared from recent apps. Here is my code:

Dagger App Module:

```<code>@Module
class AppModule {

    @Provides
    @Singleton
    fun database(context: Context) = Room
         .databaseBuilder(context, MyDatabase::class.java, "my_db.db").build()

}
</code>```

Dagger App Component:

```<code>@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance context: Context): AppComponent
    }

    fun getDatabase(): MyDatabase

}
</code>```

Application class:

```<code>class App : Application() {

    override fun onCreate() {
        super.onCreate()
        appComponent = DaggerAppComponent.factory().create(applicationContext)
    }

    companion object {
        lateinit var appComponent: AppComponent
    }
}
</code>```

Foreground service notification:

```<code>val intent = Intent(applicationContext, MyBroadcastReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
    applicationContext,
    0,
    stopIntent,
    PendingIntent.FLAG_UPDATE_CURRENT
)

val notification = NotificationCompat
    .Builder(applicationContext, "channel_id")
    ......
    .addAction(0, "button text", pendingIntent)
    ......
    .build()
</code>```

BroadcastReceiver:

```<code>class MyBroadcastReceiver : BroadcastReceiver() {

    @Inject
    lateinit var database: MyDatabase

    override fun onReceive(context: Context?, intent: Intent?) {
        database = App.appComponent.getDatabase()
        //Write something to database
    }
}
</code>```

Previous code is working perfectly even if app is completely killed. I just want to now how is it possible for me to access appComponent after app is being killed? Am I using a standard solution? Is anything wrong with my code? Is there a better way to do this?

答:
As EpicPandaForce mentioned in comments, swiping the app away in recents only kills the task, not the application process.  Your app process can be killed regardless of whether the task is destroyed.  Furthermore, if you have a foreground service running, you know that the app hasn't been destroyed yet.

This isn't the only reason you can access your Room database.

If your broadcast receiver is running, then your app has been created

Suppose you just have a notification without a foreground service.  It is possible that your app will be killed in the background, and the notification will still be around.  What happens if you click the button on the notification now?

As stated in the documentation for Application.onCreate():

Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.

Implementations should be as quick as possible (for example using lazy initialization of state) since the time spent in this function directly impacts the performance of starting the first activity, service, or receiver in a process.

By the time Android instantiates your BroadcastReceiver, the newly recreated application process has already called App.onCreate(), so you will have access to the Room database via a new instance of AppComponent.

Body:
I just started using Dagger library. I've created an AppComponent where I hold a singleton instance of my room database. I have a foreground service which needs to write something to room database when its notification button is clicked. As you know foreground service notification is always visible to user even if the user closes app and I thought if my app gets killed, the AppComponent will no longer be usable. But now I can access it and get the database instance when service notification button is clicked, even if my app has been cleared from recent apps. Here is my code:

Dagger App Module:

@Module
class AppModule {

    @Provides
    @Singleton
    fun database(context: Context) = Room
         .databaseBuilder(context, MyDatabase::class.java, "my_db.db").build()

}

Dagger App Component:

@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance context: Context): AppComponent
    }

    fun getDatabase(): MyDatabase

}

Application class:

class App : Application() {

    override fun onCreate() {
        super.onCreate()
        appComponent = DaggerAppComponent.factory().create(applicationContext)
    }

    companion object {
        lateinit var appComponent: AppComponent
    }
}

Foreground service notification:

val intent = Intent(applicationContext, MyBroadcastReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
    applicationContext,
    0,
    stopIntent,
    PendingIntent.FLAG_UPDATE_CURRENT
)

val notification = NotificationCompat
    .Builder(applicationContext, "channel_id")
    ......
    .addAction(0, "button text", pendingIntent)
    ......
    .build()

BroadcastReceiver:

class MyBroadcastReceiver : BroadcastReceiver() {

    @Inject
    lateinit var database: MyDatabase

    override fun onReceive(context: Context?, intent: Intent?) {
        database = App.appComponent.getDatabase()
        //Write something to database
    }
}

Previous code is working perfectly even if app is completely killed. I just want to now how is it possible for me to access appComponent after app is being killed? Am I using a standard solution? Is anything wrong with my code? Is there a better way to do this?


问:
Python append array to array in loop
I'm coming from PHP to python.

In PHP i do this:

```<code>$result = array();

foreach($videos as $video) {
  $result[] = array("title"=>$video->title,"description"=>$video->title);
}

print_r($result);
</code>```

Now when i try this in python flask i get an error We're sorry, but something went wrong: Web application could not be started

```<code>result = {}

for video in videos:
    title = video['title']
    description = video['description']
    content = {'title':title, 'description': description}
    result[] = content
</code>```

How do i solve?

Here is full function

```<code>@app.route("/add_channel", methods=['POST'])
def add_channel():
    if request.method == "POST":
        id=request.form['channel']
        videos = get_channel_videos(id)

         result = []
         for video in videos:
             result.append({'id': video['id'], 'title': video['snippet']['title']})
    return result
</code>```

答:
If your final result is a list of dictionaries, that last line would be

```<code>result.append(content)
</code>```

More concisely that could be achieved in a list comprehension

```<code>result = [{'title': video['title'], 'description': video['description']} for video in videos]
</code>```

Title: Python append array to array in loop

Body:
I'm coming from PHP to python.

In PHP i do this:

$result = array();

foreach($videos as $video) {
  $result[] = array("title"=>$video->title,"description"=>$video->title);
}

print_r($result);

Now when i try this in python flask i get an error We're sorry, but something went wrong: Web application could not be started

result = {}

for video in videos:
    title = video['title']
    description = video['description']
    content = {'title':title, 'description': description}
    result[] = content

How do i solve?

Here is full function

@app.route("/add_channel", methods=['POST'])
def add_channel():
    if request.method == "POST":
        id=request.form['channel']
        videos = get_channel_videos(id)

         result = []
         for video in videos:
             result.append({'id': video['id'], 'title': video['snippet']['title']})
    return result

Body:
If your final result is a list of dictionaries, that last line would be

result.append(content)

More concisely that could be achieved in a list comprehension

result = [{'title': video['title'], 'description': video['description']} for video in videos]


问:
Json Parsing Swift using an Api (alpha vantage)

Swift Json Parse

I am trying to parse the json to assign the values. I am new to swift and cannot find the solution on YouTube or the web. I am not sure if I have to have the construct identical to what is inside the "" for the json but there is a space. Additionally I am not sure if the date is used to call the Information for the day.

```<code>struct Stock: Decodable {
let symbol: String
let open: Double
let high: Double
let low: Double
let close: Double
let volume: Int
}

var tag : String = "TSLA"

    let url =  URL(string: "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=/(key)")

    let session = URLSession.shared
        session.dataTask(with: url!) { (data, response, error) in

        // pull what is coming from the interent
        if let response = response {
            print(response)
        }

        // print the data but it wont be unpacked
        if let data = data {
            print(data)
        }

        // json serialization

        do{
            let json = try JSONSerialization.jsonObject(with: data!, options: [])
            print(json)

            let stock = try
            JSONDecoder().decode(Stock.self, from: data!)
            print(Stock.init(symbol: String, open: Double, high: Double, low: Double, close: Double, volume: Int))

        } catch {
            print(error)
            }

}.resume()
</code>```

example of the print json:

```<code>"Meta Data" =     {
        "1. Information" = "Daily Prices (open, high, low, close) and Volumes";
        "2. Symbol" = TSLA;
        "3. Last Refreshed" = "2020-06-01";
        "4. Output Size" = Compact;
        "5. Time Zone" = "US/Eastern";
    };
    "Time Series (Daily)" =     {
        "2020-01-08" =         {
            "1. open" = "473.7000";
            "2. high" = "498.4900";
            "3. low" = "468.2300";
            "4. close" = "492.1400";
            "5. volume" = 31199393;
        };
        "2020-01-09" =         {
            "1. open" = "497.1000";
            "2. high" = "498.8000";
            "3. low" = "472.8700";
            "4. close" = "481.3400";
            "5. volume" = 28463186;
        };
        "2020-01-10" =         {
            "1. open" = "481.7900";
            "2. high" = "484.9400";
            "3. low" = "473.7000";
            "4. close" = "478.1500";
            "5. volume" = 12976832;
</code>```

答:
You need to modify your struct like this and decode as follows:-

Struct:

struct Stock: Codable {
    let metaData: MetaData
    let timeSeriesDaily: [String: TimeSeriesDaily]

    enum CodingKeys: String, CodingKey {
        case metaData = "Meta Data"
        case timeSeriesDaily = "Time Series (Daily)"
    }
}

struct MetaData: Codable {
    let the1Information, the2Symbol, the3LastRefreshed, the4OutputSize: String
    let the5TimeZone: String

    enum CodingKeys: String, CodingKey {
        case the1Information = "1. Information"
        case the2Symbol = "2. Symbol"
        case the3LastRefreshed = "3. Last Refreshed"
        case the4OutputSize = "4. Output Size"
        case the5TimeZone = "5. Time Zone"
    }
}

struct TimeSeriesDaily: Codable {
    let the1Open, the2High, the3Low, the4Close: String
    let the5Volume: String

    enum CodingKeys: String, CodingKey {
        case the1Open = "1. open"
        case the2High = "2. high"
        case the3Low = "3. low"
        case the4Close = "4. close"
        case the5Volume = "5. volume"
    }
}
```

<p>URLSession:</p>

<pre class="lang-swift prettyprint-override"><code>URLSession.shared.dataTask(with: URL(string: "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=TSLA")!) { (data, _, _) in
    let stock = try! JSONDecoder().decode(Stock.self, from: data!)
    print(stock)
}.resume()
</code>```

Note: This is just an example, you're supposed to handle the errors by your self.

Body:
Swift Json Parse

I am trying to parse the json to assign the values. I am new to swift and cannot find the solution on YouTube or the web. I am not sure if I have to have the construct identical to what is inside the "" for the json but there is a space. Additionally I am not sure if the date is used to call the Information for the day.

struct Stock: Decodable {
let symbol: String
let open: Double
let high: Double
let low: Double
let close: Double
let volume: Int
}

var tag : String = "TSLA"

    let url =  URL(string: "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=/(key)")

    let session = URLSession.shared
        session.dataTask(with: url!) { (data, response, error) in

        // pull what is coming from the interent
        if let response = response {
            print(response)
        }

        // print the data but it wont be unpacked
        if let data = data {
            print(data)
        }

        // json serialization

        do{
            let json = try JSONSerialization.jsonObject(with: data!, options: [])
            print(json)

            let stock = try
            JSONDecoder().decode(Stock.self, from: data!)
            print(Stock.init(symbol: String, open: Double, high: Double, low: Double, close: Double, volume: Int))

        } catch {
            print(error)
            }

}.resume()

example of the print json:

"Meta Data" =     {
        "1. Information" = "Daily Prices (open, high, low, close) and Volumes";
        "2. Symbol" = TSLA;
        "3. Last Refreshed" = "2020-06-01";
        "4. Output Size" = Compact;
        "5. Time Zone" = "US/Eastern";
    };
    "Time Series (Daily)" =     {
        "2020-01-08" =         {
            "1. open" = "473.7000";
            "2. high" = "498.4900";
            "3. low" = "468.2300";
            "4. close" = "492.1400";
            "5. volume" = 31199393;
        };
        "2020-01-09" =         {
            "1. open" = "497.1000";
            "2. high" = "498.8000";
            "3. low" = "472.8700";
            "4. close" = "481.3400";
            "5. volume" = 28463186;
        };
        "2020-01-10" =         {
            "1. open" = "481.7900";
            "2. high" = "484.9400";
            "3. low" = "473.7000";
            "4. close" = "478.1500";
            "5. volume" = 12976832;

Body:
You need to modify your struct like this and decode as follows:-

Struct:

struct Stock: Codable {
    let metaData: MetaData
    let timeSeriesDaily: [String: TimeSeriesDaily]

    enum CodingKeys: String, CodingKey {
        case metaData = "Meta Data"
        case timeSeriesDaily = "Time Series (Daily)"
    }
}

struct MetaData: Codable {
    let the1Information, the2Symbol, the3LastRefreshed, the4OutputSize: String
    let the5TimeZone: String

    enum CodingKeys: String, CodingKey {
        case the1Information = "1. Information"
        case the2Symbol = "2. Symbol"
        case the3LastRefreshed = "3. Last Refreshed"
        case the4OutputSize = "4. Output Size"
        case the5TimeZone = "5. Time Zone"
    }
}

struct TimeSeriesDaily: Codable {
    let the1Open, the2High, the3Low, the4Close: String
    let the5Volume: String

    enum CodingKeys: String, CodingKey {
        case the1Open = "1. open"
        case the2High = "2. high"
        case the3Low = "3. low"
        case the4Close = "4. close"
        case the5Volume = "5. volume"
    }
}

URLSession:

URLSession.shared.dataTask(with: URL(string: "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=TSLA")!) { (data, _, _) in
    let stock = try! JSONDecoder().decode(Stock.self, from: data!)
    print(stock)
}.resume()

Note: This is just an example, you're supposed to handle the errors by your self.


问:
Matlab substitution within matrices not working as intended
Where does the following matlab code go wrong?

```<code>C=sym('a',[2,1]);
A=sym('aa',2);

A(1,1)=C(1)-10*C(2)*C(2);
A(2,2)=C(2);

subs(A(1,1),C(1),solve(trace(A)==1,C(1)));

disp(A);
</code>```

As I understand it, the diagonal elements of A are set to functions of a1 and a2. Then, in the expression at position A(1,1), substitute for C(1) (which is a1), the solution to trace(A)==1 for the variable C(1). But when you display the matrix A, it seems unchanged.

What is the error? Why is subs not working as intended? The above is the smallest non-working example of large code.

答:
There is no error in the code. The subs = subs(s, old, new) function returns by definition a copy of s after all occurrences of old are replaced with new, and then evaluates s.

What your code does is: Define A, call subs and then display A. Since subs does not effect the entries of A by the above explanation, you get the "old" A displayed.

Hence, if you want to replace the value A(1, 1) with the expression which subs created for you, you should e.g. use

```<code>A(1, 1) = subs(C(1) , solve(trace(A) == 1, C(1)));
</code>```

Body:
Where does the following matlab code go wrong?

C=sym('a',[2,1]);
A=sym('aa',2);

A(1,1)=C(1)-10*C(2)*C(2);
A(2,2)=C(2);

subs(A(1,1),C(1),solve(trace(A)==1,C(1)));

disp(A);

As I understand it, the diagonal elements of A are set to functions of a1 and a2. Then, in the expression at position A(1,1), substitute for C(1) (which is a1), the solution to trace(A)==1 for the variable C(1). But when you display the matrix A, it seems unchanged.

What is the error? Why is subs not working as intended? The above is the smallest non-working example of large code.

Body:
There is no error in the code. The subs = subs(s, old, new) function returns by definition a copy of s after all occurrences of old are replaced with new, and then evaluates s.

What your code does is: Define A, call subs and then display A. Since subs does not effect the entries of A by the above explanation, you get the "old" A displayed.

Hence, if you want to replace the value A(1, 1) with the expression which subs created for you, you should e.g. use

A(1, 1) = subs(C(1) , solve(trace(A) == 1, C(1)));


问:
Prevent (Of …) auto completion in the Visual Basic editor
Repro:

Start VS 2015

Create a new VB.NET console application

Start typing inside Sub Main():

```<code>Dim s = {"a", "b"}
s.Se
</code>```

Observe that Visual Studio helpfully offers the Select extension method:

Hit ( to auto-complete and start providing parameters to the method.

Actual result: s.Select(Of …)()

Desired result: s.Select()

I don't want the (Of …) part since type inference works perfectly fine without it in 99% of the cases and it clutters my code. Is there a way to tell auto-complete not to do that?

Note: Apparently, this "issue" only affects the Enumerable.Select(Of T) and Enumerable.SelectMany(Of T) extension methods. Enumerable.Cast(Of T) and a custom Select(Of T) extension method work fine (no (Of …)).

答:
The intellisense in Visual studio select the auto complete features based on the data type.

The declaration below declares s as an object.

```<code>Dim s = {"a", "b"}
</code>```

This is the reason the intellisense list show the functions related to object. Declare s as shown below to get the right list.

```<code>Dim s As string = {"a", "b"}
</code>```

Body:
Repro:

Start VS 2015

Create a new VB.NET console application

Start typing inside Sub Main():

Dim s = {"a", "b"}
s.Se

Observe that Visual Studio helpfully offers the Select extension method:

Hit ( to auto-complete and start providing parameters to the method.

Actual result: s.Select(Of …)()

Desired result: s.Select()

I don't want the (Of …) part since type inference works perfectly fine without it in 99% of the cases and it clutters my code. Is there a way to tell auto-complete not to do that?

Note: Apparently, this "issue" only affects the Enumerable.Select(Of T) and Enumerable.SelectMany(Of T) extension methods. Enumerable.Cast(Of T) and a custom Select(Of T) extension method work fine (no (Of …)).

Body:
The intellisense in Visual studio select the auto complete features based on the data type.

The declaration below declares s as an object.

Dim s = {"a", "b"}

This is the reason the intellisense list show the functions related to object. Declare s as shown below to get the right list.

Dim s As string = {"a", "b"}


问:
How to set Minimum and Maximum limit to Uitextfield?
i need to set minimum and maximum limit value to one single textfield i.e the number should start with minimum 2 digits and maximum 5 digits here i tried some methods

```<code>-(BOOL)validatenumber:(NSString*)Number{

if ([Number length ]>=2)  {
    return NO;
}

return YES;
</code>```

}

答:
Try this out with slight modifications as per your need. This will also handle the deletion of first element in textfield to set the minimum value and will not allow to enter less than minimum value or more than maximum value.

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if let manualInputText = textField.text, let range = Range(range, in: manualInputText) {

        let inputText = manualInputText.replacingCharacters(in: range, with: string)
        let minValue = 0 //your value
        let maxValue = 10 //your value

        if inputText.isEmpty {
            textField.text = "\(minValue)"
            return false
        } else if textField.text == "0" {
            textField.text = string
            return false
        }
        if let inputValue = Int64(inputText), (inputValue >= minValue), (inputValue <= maxValue) {
                return true
        }
    }
    return false
}
</code>```

Please comment if you need any modifications.

Body:
i need to set minimum and maximum limit value to one single textfield i.e the number should start with minimum 2 digits and maximum 5 digits here i tried some methods

-(BOOL)validatenumber:(NSString*)Number{

if ([Number length ]>=2)  {
    return NO;
}

return YES;

}

Body:
Try this out with slight modifications as per your need. This will also handle the deletion of first element in textfield to set the minimum value and will not allow to enter less than minimum value or more than maximum value.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if let manualInputText = textField.text, let range = Range(range, in: manualInputText) {

        let inputText = manualInputText.replacingCharacters(in: range, with: string)
        let minValue = 0 //your value
        let maxValue = 10 //your value

        if inputText.isEmpty {
            textField.text = "\(minValue)"
            return false
        } else if textField.text == "0" {
            textField.text = string
            return false
        }
        if let inputValue = Int64(inputText), (inputValue >= minValue), (inputValue <= maxValue) {
                return true
        }
    }
    return false
}

Please comment if you need any modifications.


答:
If you need a resource for learning about parsers, I can recommend Basics of Compiler Design, which is available as a free download.

It covers more than just parsers, but if you read the first few chapters, you should have a good basic understanding of both lexers and parsers.

Title: Java to HTML Parser / State Machine


问:
Problem to see the color preview when autocomplete
I've begun working with tailwind in my VSCode

I've installed some extensions (I had other prev. installed)

```<code>bierner.color-info
bradlc.vscode-tailwindcss
burkeholland.simple-react-snippets
christian-kohler.npm-intellisense
CoenraadS.bracket-pair-colorizer-2
dbaeumer.vscode-eslint
dsznajder.es7-react-js-snippets
EditorConfig.EditorConfig
esbenp.prettier-vscode
felixfbecker.php-intellisense
flowtype.flow-for-vscode
JakeWilson.vscode-cdnjs
MehediDracula.php-namespace-resolver
mgmcdermott.vscode-language-babel
msjsdiag.vscode-react-native
naumovs.color-highlight
NuclleaR.vscode-extension-auto-import
oderwat.indent-rainbow
PKief.material-icon-theme
royaction.color-manager
runningcoder.react-snippets
zhuangtongfa.material-theme
</code>```

My problem is that I cannot see the color preview for each class in the autocomplete list (See image)...

I've tried disabling all of them, enabling only tailwind intellisense, w/o luck

Thanks for any tip you can give me

PS: Latest VSCode version on Windows 8.1 Pro

答:
The problem was a bug in Tailwind CSS Intellisense

https://github.com/bradlc/vscode-tailwindcss/issues/113

Installing the alpha release solved it

Body:
I've begun working with tailwind in my VSCode

I've installed some extensions (I had other prev. installed)

bierner.color-info
bradlc.vscode-tailwindcss
burkeholland.simple-react-snippets
christian-kohler.npm-intellisense
CoenraadS.bracket-pair-colorizer-2
dbaeumer.vscode-eslint
dsznajder.es7-react-js-snippets
EditorConfig.EditorConfig
esbenp.prettier-vscode
felixfbecker.php-intellisense
flowtype.flow-for-vscode
JakeWilson.vscode-cdnjs
MehediDracula.php-namespace-resolver
mgmcdermott.vscode-language-babel
msjsdiag.vscode-react-native
naumovs.color-highlight
NuclleaR.vscode-extension-auto-import
oderwat.indent-rainbow
PKief.material-icon-theme
royaction.color-manager
runningcoder.react-snippets
zhuangtongfa.material-theme

My problem is that I cannot see the color preview for each class in the autocomplete list (See image)...

I've tried disabling all of them, enabling only tailwind intellisense, w/o luck

Thanks for any tip you can give me

PS: Latest VSCode version on Windows 8.1 Pro


问:
DataGridView Column format as "yyyy-mm-dd h:mm tt" does not sort correctly
I got a DataGridView with two columns.  The first column is Name and the second column is Datetime.  I load the Grid from a text file e.g. Mini Me|2020-06-01 3:22 PM
please see the code below. The Grid loads OK but it doesn't seem to sort correctly. Please see image of the first two rows sorted by descending. Could someone tell me what's wrong with it?

```<code>            dataGridView1.Columns[1].DefaultCellStyle.Format = "yyyy'-'MM'-'dd h:mm tt";

        while ((newline = file.ReadLine()) != null)
        {
            DataRow dr = dt.NewRow();
            string[] values = newline.Split('|');
            for (int i = 0; i < values.Length; i++)
                if (i == 1)
                {
                    DateTime thisDT = DateTime.Parse(values[i]);
                    dr[i] = thisDT;
                }
                else
                    dr[i] = values[i];

        dt.Rows.Add (dr);
        }
</code>```

Grid Image

答:
You have mentioned the DateTime format "yyyy-mm-dd h:mm tt" in the title, but in the code you mention the format "yyyy'-'MM'-'dd hh:mm tt".

The image you show looks like the output of when you have used a single h in the DateTime format. Remember that once you mention this format, the values of DateTime.ToString(format) would be compared.

With a single h, 8:45 comes after 10:12, and hence first in descending order.
If you use the hh format instead, 08:45 would come before 10:12, and so, second in descending order.

Body:
I got a DataGridView with two columns.  The first column is Name and the second column is Datetime.  I load the Grid from a text file e.g. Mini Me|2020-06-01 3:22 PM
please see the code below. The Grid loads OK but it doesn't seem to sort correctly. Please see image of the first two rows sorted by descending. Could someone tell me what's wrong with it?

            dataGridView1.Columns[1].DefaultCellStyle.Format = "yyyy'-'MM'-'dd h:mm tt";

        while ((newline = file.ReadLine()) != null)
        {
            DataRow dr = dt.NewRow();
            string[] values = newline.Split('|');
            for (int i = 0; i < values.Length; i++)
                if (i == 1)
                {
                    DateTime thisDT = DateTime.Parse(values[i]);
                    dr[i] = thisDT;
                }
                else
                    dr[i] = values[i];

        dt.Rows.Add (dr);
        }

Grid Image


问:
How to check if $scope variable is an array?
I am trying to make a check to see if $scope.digitalSelect is an array and if it is set $scope.multiSelectas a variable

what I have so far is not much at all...

```<code>        if ($scope.digitalSelect === Array) {
        console.log('array');
    } else {
        console.log('not array');
    }
</code>```

答:
to detect if an object is an array you need to use:

```<code>if(Array.isArray($scope.digitalSelect)){
   console.log('array');
}
else {
    console.log('not array');
}
</code>```

To see if $scope.multiSelect is in the array... you would have to loop through the items in the array and see if array[index]===$scope.multiSelect.   This will only work however if $scope.multiSelect is of type Object.   JavaScript copies objects by reference but if its any other datatype then it will copy by value...  which means that the best you can do is see if the Value of $scope.multiSelect is in the array...

Body:
I am trying to make a check to see if $scope.digitalSelect is an array and if it is set $scope.multiSelectas a variable

what I have so far is not much at all...

        if ($scope.digitalSelect === Array) {
        console.log('array');
    } else {
        console.log('not array');
    }

Body:
to detect if an object is an array you need to use:

if(Array.isArray($scope.digitalSelect)){
   console.log('array');
}
else {
    console.log('not array');
}

To see if $scope.multiSelect is in the array... you would have to loop through the items in the array and see if array[index]===$scope.multiSelect.   This will only work however if $scope.multiSelect is of type Object.   JavaScript copies objects by reference but if its any other datatype then it will copy by value...  which means that the best you can do is see if the Value of $scope.multiSelect is in the array...


问:
RSelenium: configure firefox remotedriver to use Tor network
I am trying to use RSelenium with firefox using a local proxy (Tor) on a linux machine.

I had no problem in installing Tor following this tuto, and the command line wget -qO - https://api.ipify.org; echo do get me an new IP.

Now I am willing to use firefox with RSelenium going through the Tor localhost on port 9050:

```<code>State       Recv-Q Send-Q                                 Local Address:Port                                                Peer Address:Port
LISTEN      0      128                                        127.0.0.1:9050                                                           *:*
LISTEN      0      128                                        127.0.0.1:9051                                                           *:*
</code>```

I use a standalone selenium java (selenium-server-standalone-2.53.0.jar), which work fine with regular RSelenium: here is an example getting the ip displayed on ipchicken

```<code>library(RSelenium)

remDr <- remoteDriver(
  remoteServerAddr = "localhost",
  port = 4444L,
  browserName = "firefox"
)

remDr$open()
remDr$navigate("https://ipchicken.com/")
ip <- remDr$findElements(using = "css", value ='b')
print(ip[[1]]$getElementText())
</code>```

And I do get my IP. Now I want to see it happen with Tor. I thus try to add the proxy option when connecting the remotedriver with firefox:

```<code>eCaps <- list("moz:firefoxOptions" = list(
  args = c('--proxy-server=localhost:9050'
  )))

remDr <- remoteDriver(
  remoteServerAddr = "localhost",
  port = 4444L,
  browserName = "firefox",
  extraCapabilities = eCaps
)
</code>```

I tried '--proxy-server=localhost:9050', '--proxy-server=http://localhost:9050','--proxy-server=socks5://localhost:9050', '--proxy-server=127.0.0.1:9050', and it did not output any error and gave me my initial IP. So it is not working. The standalone says it does execute with the options: for example

```<code>22:59:10.288 INFO - Executing: [new session: Capabilities [{nativeEvents=true, browserName=firefox, javascriptEnabled=true, moz:firefoxOptions={args=--proxy-server= 127.0.0.1:9050}, version=, platform=ANY}]])
22:59:10.297 INFO - Creating a new session for Capabilities [{nativeEvents=true, browserName=firefox, javascriptEnabled=true, moz:firefoxOptions={args=--proxy-server= 127.0.0.1:9050}, version=, platform=ANY}]
22:59:30.323 INFO - Done: [new session: Capabilities [{nativeEvents=true, browserName=firefox, javascriptEnabled=true, moz:firefoxOptions={args=--proxy-server= 127.0.0.1:9050}, version=, platform=ANY}]]
</code>```

What Am I doing wrong ?

Edit

After user1207289's answer, and after realizing that you could directly create a firefox profile in RSelenium, I tried:

```<code>eCaps <- makeFirefoxProfile(list(network.proxy.type = 1,
                                 network.proxy.socks = "127.0.0.1",
                                 network.proxy.socks_port = 9050,
                                 network.proxy.socks_version = 5))

remDr <- remoteDriver(
  remoteServerAddr = "localhost",
  port = 4444L,
  browserName = "firefox",
  extraCapabilities = eCaps
)
</code>```

I used integer for network.proxy.socks_port, network.proxy.socks_port and network.proxy.type because of this question, but tried with character also, without any success. I tried with and without network.proxy.socks_version = 5, and it did not work (I am getting my normal ip). I tried network.proxy.socks_port = 9150, but it did not work.

I also tried

```<code>eCaps <- list("moz:firefoxOptions" = list(
  args = c('network.proxy.socks=127.0.0.1:9050' ,'network.proxy.type=1' )
)
)
</code>```

but that did not work either.

答:
I could connect to TOR using webdriver and firefox with the below . Just make sure TOR is installed and running. I used it on mac (catalina). You can check port settings according to your OS , in case they are different.

It is in c# but you can pretty much do it for any binding

```<code>            FirefoxOptions firefoxOptions = new FirefoxOptions();
            firefoxOptions.SetPreference("network.proxy.type", 1);
            firefoxOptions.SetPreference("network.proxy.socks", "127.0.0.1");
            firefoxOptions.SetPreference("network.proxy.socks_port", 9150);

            FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();

            IWebDriver driver = new FirefoxDriver(service, firefoxOptions);
</code>```

When this opens a firefox browser instance , Just visit https://check.torproject.org/ on the same instance to check if it is connected to TOR. And that will confirm you are connected and will show your new ip also

Body:
I am trying to use RSelenium with firefox using a local proxy (Tor) on a linux machine.

I had no problem in installing Tor following this tuto, and the command line wget -qO - https://api.ipify.org; echo do get me an new IP.

Now I am willing to use firefox with RSelenium going through the Tor localhost on port 9050:

State       Recv-Q Send-Q                                 Local Address:Port                                                Peer Address:Port
LISTEN      0      128                                        127.0.0.1:9050                                                           *:*
LISTEN      0      128                                        127.0.0.1:9051                                                           *:*

I use a standalone selenium java (selenium-server-standalone-2.53.0.jar), which work fine with regular RSelenium: here is an example getting the ip displayed on ipchicken

library(RSelenium)

remDr <- remoteDriver(
  remoteServerAddr = "localhost",
  port = 4444L,
  browserName = "firefox"
)

remDr$open()
remDr$navigate("https://ipchicken.com/")
ip <- remDr$findElements(using = "css", value ='b')
print(ip[[1]]$getElementText())

And I do get my IP. Now I want to see it happen with Tor. I thus try to add the proxy option when connecting the remotedriver with firefox:

eCaps <- list("moz:firefoxOptions" = list(
  args = c('--proxy-server=localhost:9050'
  )))

remDr <- remoteDriver(
  remoteServerAddr = "localhost",
  port = 4444L,
  browserName = "firefox",
  extraCapabilities = eCaps
)

I tried '--proxy-server=localhost:9050', '--proxy-server=http://localhost:9050','--proxy-server=socks5://localhost:9050', '--proxy-server=127.0.0.1:9050', and it did not output any error and gave me my initial IP. So it is not working. The standalone says it does execute with the options: for example

22:59:10.288 INFO - Executing: [new session: Capabilities [{nativeEvents=true, browserName=firefox, javascriptEnabled=true, moz:firefoxOptions={args=--proxy-server= 127.0.0.1:9050}, version=, platform=ANY}]])
22:59:10.297 INFO - Creating a new session for Capabilities [{nativeEvents=true, browserName=firefox, javascriptEnabled=true, moz:firefoxOptions={args=--proxy-server= 127.0.0.1:9050}, version=, platform=ANY}]
22:59:30.323 INFO - Done: [new session: Capabilities [{nativeEvents=true, browserName=firefox, javascriptEnabled=true, moz:firefoxOptions={args=--proxy-server= 127.0.0.1:9050}, version=, platform=ANY}]]

What Am I doing wrong ?

Edit

After user1207289's answer, and after realizing that you could directly create a firefox profile in RSelenium, I tried:

eCaps <- makeFirefoxProfile(list(network.proxy.type = 1,
                                 network.proxy.socks = "127.0.0.1",
                                 network.proxy.socks_port = 9050,
                                 network.proxy.socks_version = 5))

remDr <- remoteDriver(
  remoteServerAddr = "localhost",
  port = 4444L,
  browserName = "firefox",
  extraCapabilities = eCaps
)

I used integer for network.proxy.socks_port, network.proxy.socks_port and network.proxy.type because of this question, but tried with character also, without any success. I tried with and without network.proxy.socks_version = 5, and it did not work (I am getting my normal ip). I tried network.proxy.socks_port = 9150, but it did not work.

I also tried

eCaps <- list("moz:firefoxOptions" = list(
  args = c('network.proxy.socks=127.0.0.1:9050' ,'network.proxy.type=1' )
)
)

but that did not work either.

Body:
I could connect to TOR using webdriver and firefox with the below . Just make sure TOR is installed and running. I used it on mac (catalina). You can check port settings according to your OS , in case they are different.

It is in c# but you can pretty much do it for any binding

            FirefoxOptions firefoxOptions = new FirefoxOptions();
            firefoxOptions.SetPreference("network.proxy.type", 1);
            firefoxOptions.SetPreference("network.proxy.socks", "127.0.0.1");
            firefoxOptions.SetPreference("network.proxy.socks_port", 9150);

            FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();

            IWebDriver driver = new FirefoxDriver(service, firefoxOptions);

When this opens a firefox browser instance , Just visit https://check.torproject.org/ on the same instance to check if it is connected to TOR. And that will confirm you are connected and will show your new ip also


问:
Is it possible to pass a string variable as a file in command line argument?
I'm invoking a command line child process that converts a local file to another file format. It goes like this

```<code>>myFileConversion localfile.txt convertedfile.bin
</code>```

That would convert the localfile.txt to the needed format in a file named convertedfile.bin.
It also has an option to put the contents in stdout.
I'm running this in node js on the server and need the create the localfile.txt on the fly.

The contents of localfile.txt is just a string I dynamically generate. If possible, I would like the pass the string instead of writing the string to a file to be more efficient. How could I do this? Is it possible? Would it be faster than just writing to the local file?

答:
As Chris mentioned in the comments it may be possible to pipe the data but since I only need to save the file once, it's easier to just save the file locally and pass the name of the file.
Please post other possible answers as well!</p>

Body:
I'm invoking a command line child process that converts a local file to another file format. It goes like this

>myFileConversion localfile.txt convertedfile.bin

That would convert the localfile.txt to the needed format in a file named convertedfile.bin.
It also has an option to put the contents in stdout.
I'm running this in node js on the server and need the create the localfile.txt on the fly.

The contents of localfile.txt is just a string I dynamically generate. If possible, I would like the pass the string instead of writing the string to a file to be more efficient. How could I do this? Is it possible? Would it be faster than just writing to the local file?


问:
Dynamically Fill Out Dropdown in Dash
I have an issue that after I run my sql statement in a data frame.  I'm sure I'm missing something easy but its holding me up big time and I'm having issues getting my dashboard project even off the ground.

In the below code All I can get in the dropdown is UNUM when I run it and I can't figure out what I'm doing wrong to get my values out of it.  I can print eqids with no issue but I can't iterate over it correctly.  Thanks for the assistance

```<code>import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table

import pandas as pd
import sqlite3

import plotly.graph_objs as go

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

conn = sqlite3.connect(
    r"mysqlfile")
c = conn.cursor()

eqids = pd.read_sql("SELECT distinct UNUM FROM AllTestData", conn)
#names = list(eqids.keys())
print(eqids)
'''df = pd.read_sql("select * from AllTestData", conn)
df = df[['UNUM', 'DT_TAKEN', 'Iron', 'Chromium', 'Lead', 'Copper', 'Tin', 'Aluminum', 'Nickel', 'Silver', 'Silicon', 'boron', 'Sodium', 'Magnesium', 'Calcium', 'Barium', 'Phosphorous', 'Zinc',
         'Molybdenum', 'Tin1', 'Vandium', 'W', 'Potassium', 'Antimony', 'Lithium', 'Maganese', 'Cadmium', 'VISC40', 'TAN', 'KFISH', 'WATER', 'PC0', 'PC1', 'pc2', 'pc3', 'pc4', 'pc5', 'PCISO0', 'PCISO1', 'PCISO2']]
df.head(1)
'''

app.layout = html.Div([
    html.Label('Select Equipment ID'),
    dcc.Dropdown(
        id='equipment-list',
        options=[{'label': i, 'value': i} for i in eqids],
    ),
    dcc.Graph(id='test-graph')
    # html.Div(id='test-graph')
])

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

答: doh, I needed this eqids.UNUM in my options code.</p>

Title: Dynamically Fill Out Dropdown in Dash

Body:
I have an issue that after I run my sql statement in a data frame.  I'm sure I'm missing something easy but its holding me up big time and I'm having issues getting my dashboard project even off the ground.

In the below code All I can get in the dropdown is UNUM when I run it and I can't figure out what I'm doing wrong to get my values out of it.  I can print eqids with no issue but I can't iterate over it correctly.  Thanks for the assistance

import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table

import pandas as pd
import sqlite3

import plotly.graph_objs as go

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

conn = sqlite3.connect(
    r"mysqlfile")
c = conn.cursor()

eqids = pd.read_sql("SELECT distinct UNUM FROM AllTestData", conn)
#names = list(eqids.keys())
print(eqids)
'''df = pd.read_sql("select * from AllTestData", conn)
df = df[['UNUM', 'DT_TAKEN', 'Iron', 'Chromium', 'Lead', 'Copper', 'Tin', 'Aluminum', 'Nickel', 'Silver', 'Silicon', 'boron', 'Sodium', 'Magnesium', 'Calcium', 'Barium', 'Phosphorous', 'Zinc',
         'Molybdenum', 'Tin1', 'Vandium', 'W', 'Potassium', 'Antimony', 'Lithium', 'Maganese', 'Cadmium', 'VISC40', 'TAN', 'KFISH', 'WATER', 'PC0', 'PC1', 'pc2', 'pc3', 'pc4', 'pc5', 'PCISO0', 'PCISO1', 'PCISO2']]
df.head(1)
'''

app.layout = html.Div([
    html.Label('Select Equipment ID'),
    dcc.Dropdown(
        id='equipment-list',
        options=[{'label': i, 'value': i} for i in eqids],
    ),
    dcc.Graph(id='test-graph')
    # html.Div(id='test-graph')
])

if __name__ == '__main__':
    app.run_server(debug=True)


问:
Need some advice to choose the proper container
I'm trying to design a task scheduler to a game engine. A task could be an animation, a trigger controller, etc.

My problem is what container to choose. The idea is: when you insert a new task, the container must reorder and put the task in the proper place. Once executed, task could change and be scheduled again or deleted. This is mainly push and pop.

But, if possible, it would be nice if I could have random access to an element, but not vital. No matter if the container supports one or more elements with the same key.

I think that priority queue fits my needs but I saw that is based on vector implementation, and I think that this container must be somehow  optimized to push and pop.

Opinions?

答:
The vector is optimized for push and pop at one end. :-)

To prioritize you will have to sort the tasks. A vector isn't that bad, if the number of objects is reasonably small, even if it means copying objects during the sort.

Other containers, like linked lists, instead suffer from the need to allocate a new node for each object.


问:
How to commit bundle files (that are really directories) as binaries into Git
There are bundle files on macOS that are really directories but are treated as single files by their corresponding applications (e.g. a .app or an iPhoto library). Is there way to commit them to a git repo as a single binary file? Would that even make sense? I tried marking them as binaries in .gitattributes but that doesn't work.

答:
From the developer documentation:

A package is any directory that the Finder presents to the user as if it were a single file.

A bundle is a directory with a standardized hierarchical structure that holds executable code and the resources used by that code.

and

The Finder considers a directory to be a package if any of the following conditions are true:

The directory has a known filename extension: .app, .bundle,
.framework, .plugin, .kext, and so on.

The directory has an extension
that some other application claims represents a package type; see
Document Packages.

The directory has its package bit set.

This suggests that in Git, it really is just a directory with a specific set of subdirectories and files. A bundle isn't a special file, just a directory that the Finder treats specially.


问:
Pickle or json?
I need to save to disk a little dict object whose keys are of the type str and values are ints and then recover it. Something like this:

```<code>{'juanjo': 2, 'pedro':99, 'other': 333}
</code>```

What is the best option and why? Serialize it with pickle or with simplejson?

I am using Python 2.6.

答: You might also find this interesting, with some charts to compare: http://kovshenin.com/archives/pickle-vs-json-which-is-faster/</p>

Title: Pickle or json?

Body:
I need to save to disk a little dict object whose keys are of the type str and values are ints and then recover it. Something like this:

{'juanjo': 2, 'pedro':99, 'other': 333}

What is the best option and why? Serialize it with pickle or with simplejson?

I am using Python 2.6.


问:
Maven(pom.xml) do not run a plugin during deploy/install phase
If I have a pom.xml with the following code:

```<code><build>
<plugins>
    <plugin>
        <groupId>something</groupId>
        <artifactId>XXX</artifactId>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>generate</goal>
                </goals>
                <configuration>
                    ...
                </configuration>
            </execution>
  </executions>
 </plugins>
 </build>
</code>```

When I run mvn clean package, I want to run that plugin(which actually runs).

but

If I run mvn clean deploy, given phase package is previous to phase deploy is gonna run either(which I don't want to).

Is there any way to not run this plugin during deploy?

By the way: I cannot modify the mvn command executed, I need to do this inside the pom.xml file

答:
The only way that I know to selectively enable a plugin is through Maven profile:

```<code><project ...>
...

<build>
...
</build>

<profiles>
    <profile>
        <id>someprofile</id>
        <build>
        <plugins>
            <plugin>
                <groupId>something</groupId>
                <artifactId>XXX</artifactId>
                ...
            </plugin>
        </plugins>
        </build>
    </profile>
</profiles>

</project>
</code>```

You would then run mvn package -Psomeprofile to run the plugin, or mvn deploy to not run it.

There are additional ways to automatically activate a profile. You will have to read the docs to see if any of those apply to you.

Body:
If I have a pom.xml with the following code:

<build>
<plugins>
    <plugin>
        <groupId>something</groupId>
        <artifactId>XXX</artifactId>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>generate</goal>
                </goals>
                <configuration>
                    ...
                </configuration>
            </execution>
  </executions>
 </plugins>
 </build>

When I run mvn clean package, I want to run that plugin(which actually runs).

but

If I run mvn clean deploy, given phase package is previous to phase deploy is gonna run either(which I don't want to).

Is there any way to not run this plugin during deploy?

By the way: I cannot modify the mvn command executed, I need to do this inside the pom.xml file

Body:
The only way that I know to selectively enable a plugin is through Maven profile:

<project ...>
...

<build>
...
</build>

<profiles>
    <profile>
        <id>someprofile</id>
        <build>
        <plugins>
            <plugin>
                <groupId>something</groupId>
                <artifactId>XXX</artifactId>
                ...
            </plugin>
        </plugins>
        </build>
    </profile>
</profiles>

</project>

You would then run mvn package -Psomeprofile to run the plugin, or mvn deploy to not run it.

There are additional ways to automatically activate a profile. You will have to read the docs to see if any of those apply to you.


问:
Why is there a sequence point immediately before library functions?
Standard says that:

There is a sequence point immediately before a library function returns. C17dr § 7.1.4 3.

I know that there is a sequence point before actual call and after return statement (due to semicolon if there is another reason please let me know) but i couldn't understand the sentence above. Could anyone please explain this ?

答:
It means you can write code like t = sqrt(t). It would be really annoying if you couldn't.

And the behaviour of the above would be undefined if the C standard didn't guarantee that the functions had sequencing points in prior to their returning.

Note that C standard library functions might be hardcoded by the compiler - so this is an important consideration. It also adds extra protection for the user of a standard library implementation that might implement some functions as macros (which is permitted subject to a plethora of rules).

(Note that the rule has been carried over to C++).


问:
List All Loaded/Unloaded or Both Launch Agents On macOS
I am trying to figure out how many launch agents are loaded right now using following command the it

```<code>find /System/Library/Launch* /Library/Launch* ~/Library/Launch* -name '*.plist' -exec sh -c '/usr/libexec/PlistBuddy -c "Print Label" {} && echo {}' ';' | grep -wf <(launchctl list | grep -o "\S\+\..*$") -A1

grep -B 1 -A 1 "active count = 1$" <<< "$(launchctl dumpstate)"
</code>```

but its not listed the one I am looking for.
is it correct?

答:
I had your same question and this article was super helpful. I suggest reading through it, but here's a relevant snippet:

While it’s not a simple matter for users to enumerate all the Login Items, admins can do so with a little extra work by parsing the following file, if it exists: ~/Library/ApplicationSupport/com.apple.backgroundtaskmanagementagent/backgrounditems.btm

Parsing that file is more complicated than opening it with your favorite editor. The article links to a paste bin, but this github repo is a one-stop shop. Still, the article will help a lot.

Body:
I am trying to figure out how many launch agents are loaded right now using following command the it

find /System/Library/Launch* /Library/Launch* ~/Library/Launch* -name '*.plist' -exec sh -c '/usr/libexec/PlistBuddy -c "Print Label" {} && echo {}' ';' | grep -wf <(launchctl list | grep -o "\S\+\..*$") -A1

grep -B 1 -A 1 "active count = 1$" <<< "$(launchctl dumpstate)"

but its not listed the one I am looking for.
is it correct?


问:
Are always all Data Fields of the Built-In Topics sent according to the DDS/RTPS Specification?
I'm trying to understand the RTPS and DDS Specification a bit better.

The RTPS Specification talks about "data changes" and how they are propagated, but does not exactly specify "what" is propagated (as in does it know what is transmitted and sends only the changes, or does it see the data as black box and always sends the whole thing). Now I assume that this is implementation specific.

But I want to know what behavior is dictated specifically for the built-in Topics.
The DDS Specification defines the Data Types (i.e. the Data Field Names, Type, and meaning) of several built-in Topics. Can we assume that if a single Data field is changed, all other unchanged Data Fields are also sent?

答:
The specification[s] define default values for some fields of the builtin Topic types.  A sender is allowed to omit fields, and the receiver shall assume the default value for these omitted fields.  Some fields are required for proper processing, even though there may be an implicit default value.

For example, a sample on the Subscription builtin topic may omit the 'deadline' field, and the receiver[s] will use the default deadline.period value of 'infinite'.

So, to answer your question:

"Can we assume that if a single Data field is changed, all other unchanged Data Fields are also sent?"

Not necessarily: if the other (unchanged) fields are at their default values (and are not required), they "may" not be sent.  It is perfectly legal to send them, but an implementation may choose to not send them for optimization purposes.


问:
How to remove leading zero from %m for x axis in ggplot2
How can I remove leading zeros from the x axis labels WITHOUT MANUALLY adding custom labels?</p>

```<code>   p + scale_x_date(date_labels = "%m/%d", #this generated dates like: 02/15, 03/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))
</code>```

答:
You can use:

```<code>p + scale_x_date(labels = function(z) gsub("^0", "", strftime(z, "%m/%d")),
                 date_breaks = "1 week",
                 expand = expand_scale(0, 0))
</code>```

As shown in the following reprex:

library(ggplot2)

p <- ggplot(data.frame(date = seq.Date(as.Date("2020-05-30"),
                                       as.Date("2020-07-18"), length.out = 50),
                       value = sample(50)), aes(date, value)) + geom_col()
p
```

<p><img src="https://i.imgur.com/zYXj8Ci.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>p + scale_x_date(labels = function(z) gsub("^0", "", strftime(z, "%m/%d")),
                 date_breaks = "1 week",
                 expand = expand_scale(0, 0))
</code>```

Created on 2020-06-02 by the reprex package (v0.3.0)

Body:
How can I remove leading zeros from the x axis labels WITHOUT MANUALLY adding custom labels?

   p + scale_x_date(date_labels = "%m/%d", #this generated dates like: 02/15, 03/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))

Body:
You can use:

p + scale_x_date(labels = function(z) gsub("^0", "", strftime(z, "%m/%d")),
                 date_breaks = "1 week",
                 expand = expand_scale(0, 0))

As shown in the following reprex:

library(ggplot2)

p <- ggplot(data.frame(date = seq.Date(as.Date("2020-05-30"),
                                       as.Date("2020-07-18"), length.out = 50),
                       value = sample(50)), aes(date, value)) + geom_col()
p

p + scale_x_date(labels = function(z) gsub("^0", "", strftime(z, "%m/%d")),
                 date_breaks = "1 week",
                 expand = expand_scale(0, 0))

Created on 2020-06-02 by the reprex package (v0.3.0)


问:
Getting a json from an api with fetch js
I just don't know what is wrong. I am trying to get a json from an api with fetch in javascript. This is the code:

```<code>function get(){
      fetch('http://localhost:8082/marca/listar', {
            method: 'GET',
            headers: {},
            mode: 'no-cors', // <---
            cache: 'default'
        })
        .then(Response => { return Response.json() })
        .then(data => {
            console.log(data.nombre)
        });

}
</code>```

This is the url of the api

And I get the following error:

console message image

答:
Per https://developer.mozilla.org/en-US/docs/Web/API/Body/json have you tried:</p>

```<code>response.json().then(data => {
  // do something with your data
});
</code>```

Body:
I just don't know what is wrong. I am trying to get a json from an api with fetch in javascript. This is the code:

function get(){
      fetch('http://localhost:8082/marca/listar', {
            method: 'GET',
            headers: {},
            mode: 'no-cors', // <---
            cache: 'default'
        })
        .then(Response => { return Response.json() })
        .then(data => {
            console.log(data.nombre)
        });

}

This is the url of the api

And I get the following error:

console message image

Body:
Per https://developer.mozilla.org/en-US/docs/Web/API/Body/json have you tried:

response.json().then(data => {
  // do something with your data
});