问:
adding dropdown in rails_admin other form fields of same page is not shown
I am using devise and the rails_admin gem. I want to add drop down in the from filed role of the rails_admin dashboard. I copied some code from internet to do so, but when i add this code, only the role field comes with the drop. Other input that is filed is not shown in the rails_admin dashboard.

User.rb

```<code>  rails_admin do
    create do
      field :role , :enum do
        enum do
          [['admin','admin'],['user','user']]
        end
      end
    end
  end
</code>```

Anybody knows why other users form filed is not shown in rails_Admin Dashboard after adding above code.

答:
It should be edit not create, like this</p>
```<code> rails_admin do
    edit do
      field :role , :enum do
        enum do
          [['admin','admin'],['user','user']]
        end
      end
    end
  end
</code>```

Body:
I am using devise and the rails_admin gem. I want to add drop down in the from filed role of the rails_admin dashboard. I copied some code from internet to do so, but when i add this code, only the role field comes with the drop. Other input that is filed is not shown in the rails_admin dashboard.

User.rb

  rails_admin do
    create do
      field :role , :enum do
        enum do
          [['admin','admin'],['user','user']]
        end
      end
    end
  end

Anybody knows why other users form filed is not shown in rails_Admin Dashboard after adding above code.

Body:
It should be edit not create, like this

 rails_admin do
    edit do
      field :role , :enum do
        enum do
          [['admin','admin'],['user','user']]
        end
      end
    end
  end


来源: stackexchange

问:
How to list all used operations in Tensorflow SavedModel?
If I save my model using the tensorflow.saved_model.save function in SavedModel format, how can I retrieve which Tensorflow Ops are used in this model afterwards. As the model can be restored, these operations are stored in the graph, my guess is in the saved_model.pb file. If I load this protobuf (so not the entire model) the library part of the protobuf lists these, but this is not documented and tagged as an experimental feature for now. Models created in Tensorflow 1.x won't have this part.

So what is a fast and reliable way to retrieve a list of used Operations (Like MatchingFiles or WriteFile) from a model in SavedModel format?

Right now I can freeze the entire thing, like tensorflowjs-converter does. As they also check for supported Operations. This currently does not work when an LSTM is in the model, see here. Is there a better way to do this, as the Ops are definitely in there?

An example model:

```<code>class FileReader(tf.Module):

@tf.function(input_signature=[tf.TensorSpec(name='filename', shape=[None], dtype=tf.string)])
def read_disk(self, file_name):
    input_scalar = tf.reshape(file_name, [])
    output = tf.io.read_file(input_scalar)
    return tf.stack([output], name='content')

file_reader = FileReader()

tf.saved_model.save(file_reader, 'file_reader')
</code>```

Expected in output all Ops, containing in this case at least:

ReadFile as described here

...

答:
If saved_model.pb is a SavedModel protobuf message, then you get the operations directly from there. Let's say we create a model as follows:

import tensorflow as tf

class FileReader(tf.Module):
    @tf.function(input_signature=[tf.TensorSpec(name='filename', shape=[None], dtype=tf.string)])
    def read_disk(self, file_name):
        input_scalar = tf.reshape(file_name, [])
        output = tf.io.read_file(input_scalar)
        return tf.stack([output], name='content')

file_reader = FileReader()
tf.saved_model.save(file_reader, 'tmp')
```

<p>We can now find the operations used by that model like this:</p>

<pre class="lang-py prettyprint-override"><code>from tensorflow.core.protobuf.saved_model_pb2 import SavedModel

saved_model = SavedModel()
with open('tmp/saved_model.pb', 'rb') as f:
    saved_model.ParseFromString(f.read())
model_op_names = set()
# Iterate over every metagraph in case there is more than one
for meta_graph in saved_model.meta_graphs:
    # Add operations in the graph definition
    model_op_names.update(node.op for node in meta_graph.graph_def.node)
    # Go through the functions in the graph definition
    for func in meta_graph.graph_def.library.function:
        # Add operations in each function
        model_op_names.update(node.op for node in func.node_def)
# Convert to list, sorted if you want
model_op_names = sorted(model_op_names)
print(*model_op_names, sep='\n')
# Const
# Identity
# MergeV2Checkpoints
# NoOp
# Pack
# PartitionedCall
# Placeholder
# ReadFile
# Reshape
# RestoreV2
# SaveV2
# ShardedFilename
# StatefulPartitionedCall
# StringJoin
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I save my model using the tensorflow.saved_model.save function in SavedModel format, how can I retrieve which Tensorflow Ops are used in this model afterwards. As the model can be restored, these operations are stored in the graph, my guess is in the saved_model.pb file. If I load this protobuf (so not the entire model) the library part of the protobuf lists these, but this is not documented and tagged as an experimental feature for now. Models created in Tensorflow 1.x won't have this part.

So what is a fast and reliable way to retrieve a list of used Operations (Like MatchingFiles or WriteFile) from a model in SavedModel format?

Right now I can freeze the entire thing, like tensorflowjs-converter does. As they also check for supported Operations. This currently does not work when an LSTM is in the model, see here. Is there a better way to do this, as the Ops are definitely in there?

An example model:

class FileReader(tf.Module):

@tf.function(input_signature=[tf.TensorSpec(name='filename', shape=[None], dtype=tf.string)])
def read_disk(self, file_name):
    input_scalar = tf.reshape(file_name, [])
    output = tf.io.read_file(input_scalar)
    return tf.stack([output], name='content')

file_reader = FileReader()

tf.saved_model.save(file_reader, 'file_reader')

Expected in output all Ops, containing in this case at least:

ReadFile as described here

...

Body:
If saved_model.pb is a SavedModel protobuf message, then you get the operations directly from there. Let's say we create a model as follows:

import tensorflow as tf

class FileReader(tf.Module):
    @tf.function(input_signature=[tf.TensorSpec(name='filename', shape=[None], dtype=tf.string)])
    def read_disk(self, file_name):
        input_scalar = tf.reshape(file_name, [])
        output = tf.io.read_file(input_scalar)
        return tf.stack([output], name='content')

file_reader = FileReader()
tf.saved_model.save(file_reader, 'tmp')

We can now find the operations used by that model like this:

from tensorflow.core.protobuf.saved_model_pb2 import SavedModel

saved_model = SavedModel()
with open('tmp/saved_model.pb', 'rb') as f:
    saved_model.ParseFromString(f.read())
model_op_names = set()
# Iterate over every metagraph in case there is more than one
for meta_graph in saved_model.meta_graphs:
    # Add operations in the graph definition
    model_op_names.update(node.op for node in meta_graph.graph_def.node)
    # Go through the functions in the graph definition
    for func in meta_graph.graph_def.library.function:
        # Add operations in each function
        model_op_names.update(node.op for node in func.node_def)
# Convert to list, sorted if you want
model_op_names = sorted(model_op_names)
print(*model_op_names, sep='\n')
# Const
# Identity
# MergeV2Checkpoints
# NoOp
# Pack
# PartitionedCall
# Placeholder
# ReadFile
# Reshape
# RestoreV2
# SaveV2
# ShardedFilename
# StatefulPartitionedCall
# StringJoin


问:
Regex to find a single character within a python list
I am trying to determine if a python list item has a single character in it and if so replace it with an uncontracted version. The issue I am facing is that I cannot get it to detect a single letter (X) without it converting say boxer -> bocrossbreeder

```<code>list = ['canine', 'dog', 'X', 'boxer', 'XBreed', ' x ']
list_trimmed = [re.sub(r'\040x\040', 'CrossBreed', lst) for lst in list]
</code>```

works okay for removing the ' x ' but if i try

```<code>list_trimmed = [re.sub(r'x', 'CrossBreed', lst) for lst in list]
</code>```

it creates boCrossBreeder as it detects the x in a word in the list item.

答:
You can use regex word boundaries to detect if its a single character e.g. \bx\b

See example here: https://regex101.com/r/FbtRnN/2

```<code>list = ['canine', 'dog', 'X', 'boxer', 'XBreed', ' x ']
list_trimmed = [re.sub(r'\bx\b', 'CrossBreed', lst) for lst in list]
</code>```

Body:
I am trying to determine if a python list item has a single character in it and if so replace it with an uncontracted version. The issue I am facing is that I cannot get it to detect a single letter (X) without it converting say boxer -> bocrossbreeder

list = ['canine', 'dog', 'X', 'boxer', 'XBreed', ' x ']
list_trimmed = [re.sub(r'\040x\040', 'CrossBreed', lst) for lst in list]

works okay for removing the ' x ' but if i try

list_trimmed = [re.sub(r'x', 'CrossBreed', lst) for lst in list]

it creates boCrossBreeder as it detects the x in a word in the list item.

Body:
You can use regex word boundaries to detect if its a single character e.g. \bx\b

See example here: https://regex101.com/r/FbtRnN/2

list = ['canine', 'dog', 'X', 'boxer', 'XBreed', ' x ']
list_trimmed = [re.sub(r'\bx\b', 'CrossBreed', lst) for lst in list]


问:
QListWidget selection is slowing down app?
I'm writing an app where a QListWidget is used to show gifs previews using QMovie. Everything works fine but there's an increasing slow down while I push the button and repopulate the ListWidget. I was thinking that calling QListWidget.clear() will delete the objects from memory but I'm not sure is actually happening. Maybe there's a more efficient way of doing this but I couldn't find anything elsewhere. Here's some code (I cannot give gifs files but any gif should work):

```<code>from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
import os, glob

class gifPreviewWidget(QWidget):
    def __init__(self, gifPath, parent=None):
        super(gifPreviewWidget, self).__init__(parent)
        label = QLabel()
        label.setScaledContents(True)
        movie = QMovie(gifPath)
        movie.setSpeed(100)
        label.setMovie(movie)
        movie.start()
        nameLabel = QLabel(os.path.split(gifPath)[1].split('.')[0])
        layout = QVBoxLayout()
        layout.addWidget(label)
        print(gifPath)
        self.setLayout(layout)

class gifDelegate(QItemDelegate):
    def __init__(self, parent=None, *args):
        QItemDelegate.__init__(self, parent, *args)

    def paint(self, painter, option, index):
        painter.save()

        # set background color
        painter.setPen(QPen(Qt.NoPen))

        # set selection color
        if option.state & QStyle.State_Selected:
            painter.setBrush(QBrush(Qt.blue))
        else:
            painter.setBrush(QBrush(Qt.NoBrush))
        painter.drawRect(option.rect)
        painter.restore()

class MainUiClass(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MainUiClass, self).__init__(parent)
        self.layout=QVBoxLayout()
        self.gifDelegate = gifDelegate()
        self.previewListWidget = QListWidget()
        self.previewListWidget.setViewMode(QtWidgets.QListView.IconMode)
        self.previewListWidget.setResizeMode(QListWidget.Adjust)
        self.previewListWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.previewListWidget.setMovement(QListView.Static)
        self.previewListWidget.setSpacing(1)
        self.previewListWidget.setItemDelegate(self.gifDelegate)

        self.pushButton = QPushButton('change gif dir')
        self.layout.addWidget(self.previewListWidget)
        self.layout.addWidget(self.pushButton)
        self.setLayout(self.layout)
        self.pushButton.clicked.connect(self.onCategoryClick)

    def onCategoryClick(self):
        filePath = '/PATH/TO/LOTS/OF/GIFS'
        print(filePath+'/*.gif')
        glob.glob(filePath+'/*.gif')
        if glob.glob(filePath+'/*.gif') != []:
            print('ok')
            gifList = glob.glob(filePath+'/*.gif')
            self.previewListWidget.clear()

            for gif in gifList:
                item=QListWidgetItem(self.previewListWidget)
                itemWidget = gifPreviewWidget(gif)
                item.setSizeHint(itemWidget.sizeHint())
                self.previewListWidget.addItem(item)
                self.previewListWidget.setItemWidget(item,itemWidget)

if __name__ == '__main__':
    w = MainUiClass()
    w.show()
    sys.exit(app.exec_())
</code>```

By pressing the button often, the app starts to slow down a lot.

答:
Usually, you don't have to stop QMovie explicitly when you're about to delete it anyway. But here, it does not get deleted because it is not stopped (it's still playing).

I guess that kind of unexpected behavior is what you pay for when you use a language with a garbage collector.

Solution: stop the movie when the item is deleted. Add

```<code>class gifPreviewWidget(QWidget):
    def __del__(self):
        self.movie.stop()
</code>```

Body:
I'm writing an app where a QListWidget is used to show gifs previews using QMovie. Everything works fine but there's an increasing slow down while I push the button and repopulate the ListWidget. I was thinking that calling QListWidget.clear() will delete the objects from memory but I'm not sure is actually happening. Maybe there's a more efficient way of doing this but I couldn't find anything elsewhere. Here's some code (I cannot give gifs files but any gif should work):

from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
import os, glob

class gifPreviewWidget(QWidget):
    def __init__(self, gifPath, parent=None):
        super(gifPreviewWidget, self).__init__(parent)
        label = QLabel()
        label.setScaledContents(True)
        movie = QMovie(gifPath)
        movie.setSpeed(100)
        label.setMovie(movie)
        movie.start()
        nameLabel = QLabel(os.path.split(gifPath)[1].split('.')[0])
        layout = QVBoxLayout()
        layout.addWidget(label)
        print(gifPath)
        self.setLayout(layout)

class gifDelegate(QItemDelegate):
    def __init__(self, parent=None, *args):
        QItemDelegate.__init__(self, parent, *args)

    def paint(self, painter, option, index):
        painter.save()

        # set background color
        painter.setPen(QPen(Qt.NoPen))

        # set selection color
        if option.state & QStyle.State_Selected:
            painter.setBrush(QBrush(Qt.blue))
        else:
            painter.setBrush(QBrush(Qt.NoBrush))
        painter.drawRect(option.rect)
        painter.restore()

class MainUiClass(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MainUiClass, self).__init__(parent)
        self.layout=QVBoxLayout()
        self.gifDelegate = gifDelegate()
        self.previewListWidget = QListWidget()
        self.previewListWidget.setViewMode(QtWidgets.QListView.IconMode)
        self.previewListWidget.setResizeMode(QListWidget.Adjust)
        self.previewListWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.previewListWidget.setMovement(QListView.Static)
        self.previewListWidget.setSpacing(1)
        self.previewListWidget.setItemDelegate(self.gifDelegate)

        self.pushButton = QPushButton('change gif dir')
        self.layout.addWidget(self.previewListWidget)
        self.layout.addWidget(self.pushButton)
        self.setLayout(self.layout)
        self.pushButton.clicked.connect(self.onCategoryClick)

    def onCategoryClick(self):
        filePath = '/PATH/TO/LOTS/OF/GIFS'
        print(filePath+'/*.gif')
        glob.glob(filePath+'/*.gif')
        if glob.glob(filePath+'/*.gif') != []:
            print('ok')
            gifList = glob.glob(filePath+'/*.gif')
            self.previewListWidget.clear()

            for gif in gifList:
                item=QListWidgetItem(self.previewListWidget)
                itemWidget = gifPreviewWidget(gif)
                item.setSizeHint(itemWidget.sizeHint())
                self.previewListWidget.addItem(item)
                self.previewListWidget.setItemWidget(item,itemWidget)

if __name__ == '__main__':
    w = MainUiClass()
    w.show()
    sys.exit(app.exec_())

By pressing the button often, the app starts to slow down a lot.

Body:
Usually, you don't have to stop QMovie explicitly when you're about to delete it anyway. But here, it does not get deleted because it is not stopped (it's still playing).

I guess that kind of unexpected behavior is what you pay for when you use a language with a garbage collector.

Solution: stop the movie when the item is deleted. Add

class gifPreviewWidget(QWidget):
    def __del__(self):
        self.movie.stop()


问:
p5.js mousePressed event returns Undefined
I cant get mousePressed to console log the MouseEvent. I'm not even sure if having it in the setup function is the right place?

https://codesandbox.io/embed/withered-monad-jrhyw

```<code>import React from 'react';
import Sketch from 'react-p5';

const App: React.FC = () => {
  const setup = (p5: any) => {
    canvas = p5.createCanvas(window.innerWidth, window.innerHeight);

    canvas.mouseWheel((e: MouseEvent) => {
      console.log(e); // Wheel Event
    });

    canvas.mousePressed((e: MouseEvent) => {
      console.log(e); // Undefined
    });

  };

  const draw = (p5: any) => {
    p5.background(50);
    p5.fill(0);
    p5.rect(25, 25, 50, 50);
  };

  return (
    <React.Fragment>
      <Sketch setup={setup} draw={draw} />
    </React.Fragment>
  );
};

export { App };

</code>```

答:
The readme of the react-p5 library indicates that you should use the mousePressed method as a prop, so try and define it outside of setup and then pass it:

```<code>const mp = (e: MouseEvent) => {
  console.log(e);
})

<Sketch setup={setup} draw={draw} mousePressed={mp}/>
</code>```

Nevertheless, I did try defining several other methods inside of setup and all seemed to work normally; mousePressed was the only one that required to be passed as a prop.

Body:
I cant get mousePressed to console log the MouseEvent. I'm not even sure if having it in the setup function is the right place?

https://codesandbox.io/embed/withered-monad-jrhyw

import React from 'react';
import Sketch from 'react-p5';

const App: React.FC = () => {
  const setup = (p5: any) => {
    canvas = p5.createCanvas(window.innerWidth, window.innerHeight);

    canvas.mouseWheel((e: MouseEvent) => {
      console.log(e); // Wheel Event
    });

    canvas.mousePressed((e: MouseEvent) => {
      console.log(e); // Undefined
    });

  };

  const draw = (p5: any) => {
    p5.background(50);
    p5.fill(0);
    p5.rect(25, 25, 50, 50);
  };

  return (
    <React.Fragment>
      <Sketch setup={setup} draw={draw} />
    </React.Fragment>
  );
};

export { App };

Body:
The readme of the react-p5 library indicates that you should use the mousePressed method as a prop, so try and define it outside of setup and then pass it:

const mp = (e: MouseEvent) => {
  console.log(e);
})

<Sketch setup={setup} draw={draw} mousePressed={mp}/>

Nevertheless, I did try defining several other methods inside of setup and all seemed to work normally; mousePressed was the only one that required to be passed as a prop.


问:
Identityserver 4 and Ocelot
I'm trying to use Ocelot with IS4 following
https://ocelot.readthedocs.io/en/latest/features/authentication.html

When using

```<code>public void ConfigureServices(IServiceCollection services)
{
    var authenticationProviderKey = "TestKey";

    services.AddAuthentication()
        .AddJwtBearer(authenticationProviderKey, x =>
        {
        });
}
</code>```

and use "TestKey" in ocelot.json, it throws an error when starting the application

Unable to start Ocelot, errors are: TestKey,AllowedScopes:[] is unsupported authentication provider

Any idea what's wrong? Do I need set up something in particular in my IdentityServer app?

答:
You need to add the options, e.g.:

```<code>services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        // base-address of your identityserver
        options.Authority = "https://demo.identityserver.io";

        // name of the API resource
        options.Audience = "api1";
    });
</code>```

More info at: http://docs.identityserver.io/en/latest/topics/apis.html#

You will also need to add an API resource to your Identity Server:

```<code>new ApiResource("api1", "Some API 1")
</code>```

See:

http://docs.identityserver.io/en/latest/topics/resources.html and http://docs.identityserver.io/en/latest/reference/api_resource.html#refapiresource

Title: Identityserver 4 and Ocelot

Body:
I'm trying to use Ocelot with IS4 following
https://ocelot.readthedocs.io/en/latest/features/authentication.html

When using

public void ConfigureServices(IServiceCollection services)
{
    var authenticationProviderKey = "TestKey";

    services.AddAuthentication()
        .AddJwtBearer(authenticationProviderKey, x =>
        {
        });
}

and use "TestKey" in ocelot.json, it throws an error when starting the application

Unable to start Ocelot, errors are: TestKey,AllowedScopes:[] is unsupported authentication provider

Any idea what's wrong? Do I need set up something in particular in my IdentityServer app?

Body:
You need to add the options, e.g.:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        // base-address of your identityserver
        options.Authority = "https://demo.identityserver.io";

        // name of the API resource
        options.Audience = "api1";
    });

More info at: http://docs.identityserver.io/en/latest/topics/apis.html#

You will also need to add an API resource to your Identity Server:

new ApiResource("api1", "Some API 1")

See:

http://docs.identityserver.io/en/latest/topics/resources.html and http://docs.identityserver.io/en/latest/reference/api_resource.html#refapiresource


问:
How to avoid refreshing of masterpage while navigating in site?
In my website, I have created a masterpage and attached all of my pages to it.
My masterpage structure contains a header and a footer. On the left it has a treeview control, which i have attached to all my pages, and on the right there is a contentplaceholder to show the content of respective pages.

My problem is that when I click any link in the treeview it refreshes the whole masterpage and open the respective page. I wish to avoid this refresh. Means it should show the contents of page on right side contentplaceholder without refreshing the whole page.

I have seen people suggesting to use iframes. But for using iframes I shall have to restructure my website. Is there any other solution than iframes and with minimal changes to the work that I have done?

答:
You could put the content you wish to change inside an asp:UpdatePanel that way that will be the only thing that is repainted (it uses AJAX under the hood):

http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.aspx

ContentLicense: CC BY-SA 3.0


问:
Making python wait until subprocess.call has finished its command
So this question is following on from this (Read comments aswell as that is the path I took). I just want the first call robocopy to finish executing before moving on to the rest of the code. As I want the second robocopy to just skip all of the files as they have already been copied over. However what is happening is that the rest of the script will run (ie starts the second robocopy) while the first robocopy is copying over the files. Below is the code:

```<code>call(["start", "cmd", "/K", "RoboCopy.exe", f"{self.srcEntry.get()}", f"{self.dstEntry.get()}", "*.*", "/E", "/Z", "/MT:8"], stdout=PIPE, shell=True)
temp2 = Popen(["RoboCopy.exe", f"{self.srcEntry.get()}", f"{self.dstEntry.get()}", "*.*", "/E", "/Z"], stdout=PIPE, stdin=PIPE, shell=True)
</code>```

EDIT 1:

Issue is noticeable when copying over large files. I'm thinking about putting in a sleep function which is dependent upon the total size of the files to be copied over. However this doesn't take into account upload/download speeds as the files will be transferred over a network.

答:
Try:

while temp2.poll() is not None:
    # ... do something else, sleep, etc

out, err = temp2.communicate()
```

Body:
So this question is following on from this (Read comments aswell as that is the path I took). I just want the first call robocopy to finish executing before moving on to the rest of the code. As I want the second robocopy to just skip all of the files as they have already been copied over. However what is happening is that the rest of the script will run (ie starts the second robocopy) while the first robocopy is copying over the files. Below is the code:

call(["start", "cmd", "/K", "RoboCopy.exe", f"{self.srcEntry.get()}", f"{self.dstEntry.get()}", "*.*", "/E", "/Z", "/MT:8"], stdout=PIPE, shell=True)
temp2 = Popen(["RoboCopy.exe", f"{self.srcEntry.get()}", f"{self.dstEntry.get()}", "*.*", "/E", "/Z"], stdout=PIPE, stdin=PIPE, shell=True)

EDIT 1:

Issue is noticeable when copying over large files. I'm thinking about putting in a sleep function which is dependent upon the total size of the files to be copied over. However this doesn't take into account upload/download speeds as the files will be transferred over a network.


问:
SolrHealthIndicator without deprecated CompositeHealthIndicator
I've tried to upgrade Spring Boot to 2.2.4.RELEASE version. Everzthing if fine exept problem with CompositeHealthIndicator which is deprecated.

I have this bean method

```<code>@Autowired
private HealthAggregator healthAggregator;

    @Bean
public HealthIndicator solrHealthIndicator() {
    CompositeHealthIndicator composite = new CompositeHealthIndicator(
            this.healthAggregator);
    composite.addHealthIndicator("solr1", createHealthIndicator(firstHttpSolrClient()));
    composite.addHealthIndicator("solr2", createHealthIndicator(secondHttpSolrClient()));
    composite.addHealthIndicator("querySolr", createHealthIndicator(queryHttpSolrClient()));
    return composite;
}

private CustomSolrHealthIndicator createHealthIndicator(SolrClient source) {

    try {
        return new CustomSolrHealthIndicator(source);
    } catch (Exception ex) {
        throw new IllegalStateException("Unable to create helthCheckIndicator for solr client instance.", ex);
    }
}
</code>```

That registers HealthIndicator for 3 instances of SOLR (2 indexing, 1 for query). Everything worked fine until Spring Boot update. After update the method CompositeHealthIndicator.addHealthIndicator is not present, the whole class is marked as Deprecated.

The class which is created in createHealthIndicator is like this:

```<code>    public class CustomSolrHealthIndicator extends SolrHealthIndicator {

    private final SolrClient solrClient;

    public CustomSolrHealthIndicator(SolrClient solrClient) {
        super(solrClient);
        this.solrClient = solrClient;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {

        if (!this.solrClient.getClass().isAssignableFrom(HttpSolrClient.class)) {

            super.doHealthCheck(builder);
        }

        HttpSolrClient httpSolrClient = (HttpSolrClient) this.solrClient;
        if (StringUtils.isBlank(httpSolrClient.getBaseURL())) {
            return;
        }

        super.doHealthCheck(builder);
    }
}
</code>```

Is there any easy way to transform the old way how to register the instances of SOLR i want to check if they are up or down at Spring Boot version 2.2.X?

EDIT:
 I have tried this:

```<code>@Bean
public CompositeHealthContributor solrHealthIndicator() {

    Map<String, HealthIndicator> solrIndicators = Maps.newLinkedHashMap();
    solrIndicators.put("solr1", createHealthIndicator(firstHttpSolrClient()));
    solrIndicators.put("solr2", createHealthIndicator(secondHttpSolrClient()));
    solrIndicators.put("querySolr", createHealthIndicator(queryHttpSolrClient()));

    return CompositeHealthContributor.fromMap(solrIndicators);
}

private CustomSolrHealthIndicator createHealthIndicator(SolrClient source) {

    try {
        return new CustomSolrHealthIndicator(source);
    } catch (Exception ex) {
        throw new IllegalStateException("Unable to create healthCheckIndicator for solr client instance.", ex);
    }
}
</code>```

The CustomSolrHealthIndicator has no changes against start state.

But I cannot create that bean. When calling createHealthIndicator I am getting NoClassDefFoundError

Does anyone know where the problem is?

答:
Looks like you can just use CompositeHealthContributor. It's not much different from what you have already. It appears something like this would work. You could override the functionality to add them one at a time if you'd like, also, which might be preferable if you have a large amount of configuration. Shouldn't be any harm with either approach.</p>

```<code>@Bean
public HealthIndicator solrHealthIndicator() {
    Map<String, HealthIndicator> solrIndicators;
    solrIndicators.put("solr1", createHealthIndicator(firstHttpSolrClient()));
    solrIndicators.put("solr2", createHealthIndicator(secondHttpSolrClient()));
    solrIndicators.put("querySolr", createHealthIndicator(queryHttpSolrClient()));
    return CompositeHealthContributor.fromMap(solrIndicators);
}
</code>```

Body:
I've tried to upgrade Spring Boot to 2.2.4.RELEASE version. Everzthing if fine exept problem with CompositeHealthIndicator which is deprecated.

I have this bean method

@Autowired
private HealthAggregator healthAggregator;

    @Bean
public HealthIndicator solrHealthIndicator() {
    CompositeHealthIndicator composite = new CompositeHealthIndicator(
            this.healthAggregator);
    composite.addHealthIndicator("solr1", createHealthIndicator(firstHttpSolrClient()));
    composite.addHealthIndicator("solr2", createHealthIndicator(secondHttpSolrClient()));
    composite.addHealthIndicator("querySolr", createHealthIndicator(queryHttpSolrClient()));
    return composite;
}

private CustomSolrHealthIndicator createHealthIndicator(SolrClient source) {

    try {
        return new CustomSolrHealthIndicator(source);
    } catch (Exception ex) {
        throw new IllegalStateException("Unable to create helthCheckIndicator for solr client instance.", ex);
    }
}

That registers HealthIndicator for 3 instances of SOLR (2 indexing, 1 for query). Everything worked fine until Spring Boot update. After update the method CompositeHealthIndicator.addHealthIndicator is not present, the whole class is marked as Deprecated.

The class which is created in createHealthIndicator is like this:

    public class CustomSolrHealthIndicator extends SolrHealthIndicator {

    private final SolrClient solrClient;

    public CustomSolrHealthIndicator(SolrClient solrClient) {
        super(solrClient);
        this.solrClient = solrClient;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {

        if (!this.solrClient.getClass().isAssignableFrom(HttpSolrClient.class)) {

            super.doHealthCheck(builder);
        }

        HttpSolrClient httpSolrClient = (HttpSolrClient) this.solrClient;
        if (StringUtils.isBlank(httpSolrClient.getBaseURL())) {
            return;
        }

        super.doHealthCheck(builder);
    }
}

Is there any easy way to transform the old way how to register the instances of SOLR i want to check if they are up or down at Spring Boot version 2.2.X?

EDIT:
 I have tried this:

@Bean
public CompositeHealthContributor solrHealthIndicator() {

    Map<String, HealthIndicator> solrIndicators = Maps.newLinkedHashMap();
    solrIndicators.put("solr1", createHealthIndicator(firstHttpSolrClient()));
    solrIndicators.put("solr2", createHealthIndicator(secondHttpSolrClient()));
    solrIndicators.put("querySolr", createHealthIndicator(queryHttpSolrClient()));

    return CompositeHealthContributor.fromMap(solrIndicators);
}

private CustomSolrHealthIndicator createHealthIndicator(SolrClient source) {

    try {
        return new CustomSolrHealthIndicator(source);
    } catch (Exception ex) {
        throw new IllegalStateException("Unable to create healthCheckIndicator for solr client instance.", ex);
    }
}

The CustomSolrHealthIndicator has no changes against start state.

But I cannot create that bean. When calling createHealthIndicator I am getting NoClassDefFoundError

Does anyone know where the problem is?

Body:
Looks like you can just use CompositeHealthContributor. It's not much different from what you have already. It appears something like this would work. You could override the functionality to add them one at a time if you'd like, also, which might be preferable if you have a large amount of configuration. Shouldn't be any harm with either approach.

@Bean
public HealthIndicator solrHealthIndicator() {
    Map<String, HealthIndicator> solrIndicators;
    solrIndicators.put("solr1", createHealthIndicator(firstHttpSolrClient()));
    solrIndicators.put("solr2", createHealthIndicator(secondHttpSolrClient()));
    solrIndicators.put("querySolr", createHealthIndicator(queryHttpSolrClient()));
    return CompositeHealthContributor.fromMap(solrIndicators);
}


问:
Select one record from left table, but multiple from right table
I have two tables, where I want to select all the data where it matches on identifier, however I want to replace the repeated data collected from table A to NULL. My current result is shown in the Current Table (refer to attached image). I want results displayed as shown in New Table.

My Current SQL is:

```<code>SELECT
a.name, a.desc, b.seq
from table_a a, table_b b
where a.name = b.name
</code>```

I believe I can possibly do this by using CASE:

```<code>CASE
WHEN
b.seq = 1 THEN a.name, a.desc ELSE a.name IS NULL, a.desc IS NULL
END
</code>```

But I'm not having any luck. Any help please?

Thank you!

答:
Use the CASE clause:

```<code>select
  case when b.seq = 1 then a.name end,
  case when b.seq = 1 then a.desc end,
  b.seq
from table_a a
join table_b b on a.name = b.name
</code>```

Body:
I have two tables, where I want to select all the data where it matches on identifier, however I want to replace the repeated data collected from table A to NULL. My current result is shown in the Current Table (refer to attached image). I want results displayed as shown in New Table.

My Current SQL is:

SELECT
a.name, a.desc, b.seq
from table_a a, table_b b
where a.name = b.name

I believe I can possibly do this by using CASE:

CASE
WHEN
b.seq = 1 THEN a.name, a.desc ELSE a.name IS NULL, a.desc IS NULL
END

But I'm not having any luck. Any help please?

Thank you!

Body:
Use the CASE clause:

select
  case when b.seq = 1 then a.name end,
  case when b.seq = 1 then a.desc end,
  b.seq
from table_a a
join table_b b on a.name = b.name


问:
Creating a reactive R item that will change which variable from a dataset is used based on a selection from a text box in the UI
I am just starting out with R shiny and have been able to create some nice reactive text boxes to change displays etc.

I am now looking to do a similar thing but to read in a certain variable form my dataset depending on which variable is typed in my text box.

The standard R code to create the xvar object containing the variable AGE from my input dataset pauldata works fine. I can then go onto to use this variable in my plot no worries.

```<code>xvar <- pauldata$AGE
</code>```

However, now I wanted to change what variable is read in from my pauldata dataset based on what is entered in my text box object called xv (in this case I would enter AGE in the text box)

I tried this:

```<code>xvar2 <- reactive({pauldata$input$xv})
</code>```

Logically, I felt that this would work and then I can later use xvar2 (or maybe x2var()) in my plot statement where xvar was previously.

If I try this then I get errors relating to the length of y an x not being equal in my plot, hence I do not think that xvar2 has been assigned how I intend it to be.

I assume it is possible to read in datasets and then make variable selection from that dataset be reactive to entries in your UI?

答:
Values from a selectInput are returned as a character vector, so you need to use the [[ operator instead of the $. Also input values are also already reactive so no need to wrap in reactive()

I think this is what you were trying to accomplish:

```<code>library(shiny)

ui <- fluidPage(

  h1("Everyone's 2nd Favorite Data Set"),
  selectInput("xv", "Select Variable", choices = names(iris[-5])),
  plotOutput("plot")

)

server <- function(input, output, session) {

  output$plot <- renderPlot({
    hist(iris[[input$xv]], xlab = input$xv, main = "")
  })

}

shinyApp(ui, server)
</code>```

Body:
I am just starting out with R shiny and have been able to create some nice reactive text boxes to change displays etc.

I am now looking to do a similar thing but to read in a certain variable form my dataset depending on which variable is typed in my text box.

The standard R code to create the xvar object containing the variable AGE from my input dataset pauldata works fine. I can then go onto to use this variable in my plot no worries.

xvar <- pauldata$AGE

However, now I wanted to change what variable is read in from my pauldata dataset based on what is entered in my text box object called xv (in this case I would enter AGE in the text box)

I tried this:

xvar2 <- reactive({pauldata$input$xv})

Logically, I felt that this would work and then I can later use xvar2 (or maybe x2var()) in my plot statement where xvar was previously.

If I try this then I get errors relating to the length of y an x not being equal in my plot, hence I do not think that xvar2 has been assigned how I intend it to be.

I assume it is possible to read in datasets and then make variable selection from that dataset be reactive to entries in your UI?

Body:
Values from a selectInput are returned as a character vector, so you need to use the [[ operator instead of the $. Also input values are also already reactive so no need to wrap in reactive()

I think this is what you were trying to accomplish:

library(shiny)

ui <- fluidPage(

  h1("Everyone's 2nd Favorite Data Set"),
  selectInput("xv", "Select Variable", choices = names(iris[-5])),
  plotOutput("plot")

)

server <- function(input, output, session) {

  output$plot <- renderPlot({
    hist(iris[[input$xv]], xlab = input$xv, main = "")
  })

}

shinyApp(ui, server)


问:
Create new column with categorical variables based on date range
If I have a data from like this with lets day timeseries dates for a year (2019) -

```<code>datetime
0   15.02.19 13:00
1   15.02.19 14:00
2   15.02.19 15:00
3   15.02.19 16:00
4   15.02.19 17:00

</code>```

And I want to create a new column which has the value 'school holiday' if my datetime is within a range (school holiday dates from 2019) and 'term time' otherwise how would I approach this in the most efficient way possible? The resultant dataframe should look something like this-

```<code>datetime    school holiday
0   15.02.19 13:00  Term time
1   15.02.19 14:00  Term time
2   15.02.19 15:00  Term time
3   15.02.19 16:00  Term time
4   15.02.19 17:00  School Holiday
</code>```

My thoughts were that I would take the school holiday dates which would be something like this:

```<code>Autumn Half Term Holidays   21 Oct 2019 - 25 Oct 2019
Winter Holidays             23 Dec 2019 - 3 Jan 2020
etc...
</code>```

And make a dictionary with these dates, then somehow use lamba apply? Essentially the function should be - if datetime == holiday_range: 'school holiday' else: 'Term time'.

Thanks for your help

答:
You likely have more rows in your DataFrame than unique Holidays. For problems like this you'll probably need to loop somewhere, so better to loop over the smaller number of Holidays

Convert your dates to datetime dtype and let's store the Holidays in a separate DataFrame, again with a datetime dtype

```<code>import pandas as pd
df['datetime'] = pd.to_datetime(df['datetime'], format='%d.%m.%y %H:%M')

df2 = pd.DataFrame({'Holiday': ['Autumn Half Term Holidays', 'Winter Holidays'],
                    'start': pd.to_datetime(['2019-10-21', '2019-12-23']),
                    'end': pd.to_datetime(['2019-10-25', '2020-01-03'])})
</code>```

Now to determine if something is a holiday, we check if the datetime is between any of the periods. The map just gets your labels instead of True/False. I added a row to your example given your holidays just to illustrate that it works.

```<code>df['holiday'] = (pd.concat([df['datetime'].between(start, end) for start,end in zip(df2.start, df2.end)], 1)
                   .any(1)
                   .map({True: 'School Holiday', False: 'Term time'}))

             datetime         holiday
0 2020-01-01 01:00:00  School Holiday
1 2019-02-15 13:00:00       Term time
2 2019-02-15 14:00:00       Term time
3 2019-02-15 15:00:00       Term time
4 2019-02-15 16:00:00       Term time
5 2019-02-15 17:00:00       Term time
</code>```

Body:
If I have a data from like this with lets day timeseries dates for a year (2019) -

datetime
0   15.02.19 13:00
1   15.02.19 14:00
2   15.02.19 15:00
3   15.02.19 16:00
4   15.02.19 17:00

And I want to create a new column which has the value 'school holiday' if my datetime is within a range (school holiday dates from 2019) and 'term time' otherwise how would I approach this in the most efficient way possible? The resultant dataframe should look something like this-

datetime    school holiday
0   15.02.19 13:00  Term time
1   15.02.19 14:00  Term time
2   15.02.19 15:00  Term time
3   15.02.19 16:00  Term time
4   15.02.19 17:00  School Holiday

My thoughts were that I would take the school holiday dates which would be something like this:

Autumn Half Term Holidays   21 Oct 2019 - 25 Oct 2019
Winter Holidays             23 Dec 2019 - 3 Jan 2020
etc...

And make a dictionary with these dates, then somehow use lamba apply? Essentially the function should be - if datetime == holiday_range: 'school holiday' else: 'Term time'.

Thanks for your help

Body:
You likely have more rows in your DataFrame than unique Holidays. For problems like this you'll probably need to loop somewhere, so better to loop over the smaller number of Holidays

Convert your dates to datetime dtype and let's store the Holidays in a separate DataFrame, again with a datetime dtype

import pandas as pd
df['datetime'] = pd.to_datetime(df['datetime'], format='%d.%m.%y %H:%M')

df2 = pd.DataFrame({'Holiday': ['Autumn Half Term Holidays', 'Winter Holidays'],
                    'start': pd.to_datetime(['2019-10-21', '2019-12-23']),
                    'end': pd.to_datetime(['2019-10-25', '2020-01-03'])})

Now to determine if something is a holiday, we check if the datetime is between any of the periods. The map just gets your labels instead of True/False. I added a row to your example given your holidays just to illustrate that it works.

df['holiday'] = (pd.concat([df['datetime'].between(start, end) for start,end in zip(df2.start, df2.end)], 1)
                   .any(1)
                   .map({True: 'School Holiday', False: 'Term time'}))

             datetime         holiday
0 2020-01-01 01:00:00  School Holiday
1 2019-02-15 13:00:00       Term time
2 2019-02-15 14:00:00       Term time
3 2019-02-15 15:00:00       Term time
4 2019-02-15 16:00:00       Term time
5 2019-02-15 17:00:00       Term time


问:
how to use ansible to execute shell script against gce instances
how to use ansible to execute shell script against gce instances.
I have a service account and it has compute admin permission.

How to write ansible playbook so that i can execute shell scripts against all vm in my gcp project.

Below links don't help me too much
https://docs.ansible.com/ansible/latest/modules/gce_module.html#
https://docs.ansible.com/ansible/latest/scenario_guides/guide_gce.html#gce-dynamic-inventory

I prefer ansible because it's agentless. I don't want to install any process in those vm because they're production servers.

答:
Finally I figure it out

Here is my project:

```<code>ansible-workplace
- .gitignore
- ansible.cfg
- inventory.gcp.yaml
- main.yaml
- requirements.txt
</code>```

ansible.cfg

[defaults]
inventory = inventory.gcp.yaml
host_key_checking = False
private_key_file = /Users/<your user>/.ssh/google_compute_engine
[inventory]
enable_plugins =  host_list, script, auto, yaml, ini, toml, gcp_compute
```
<p>inventory.gcp.yaml</p>
<pre class="lang-yaml prettyprint-override"><code>plugin: gcp_compute
projects:
  - gcp-project1
  - gcp-project2
auth_kind: serviceaccount
service_account_file: /Users/<your user>/.ssh/temp-serviceaccount.json
</code>```

main.yaml

- name: echo
  hosts: all
  gather_facts: yes

  tasks:
  - name: Manage instances
    # connection: ssh
    shell: |
      server_name=`hostname`
      echo $server_name checking legacy-endpoint-access/0.1
      leg1=$(curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/legacy-endpoint-access/0.1)
      echo $leg1
      echo $server_name checking legacy-endpoint-access/v1beta1
      leg2=$(curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/legacy-endpoint-access/v1beta1)
      echo $leg2
    register: out
  - debug: var=out.stdout_lines
```
<p>By default ansible will not use gcloud generated ssh key to connect to GCE instances. So you may need to do below.
"gcloud compute config-ssh" will add hostnames to your ~/.ssh/config and you can now more easily connect to gce instances and most importantly, you figure the compute key that ansible should use to connect to gce instances.
So in ansible.cfg, this line is crucial
"private_key_file = /Users//.ssh/google_compute_engine"</p>
```gcloud compute config-ssh --remove
gcloud compute config-ssh
ansible-playbook main.yaml

```

Now you can happily run "ansible-playbook main.yaml"

Body:
Finally I figure it out

Here is my project:

ansible-workplace
- .gitignore
- ansible.cfg
- inventory.gcp.yaml
- main.yaml
- requirements.txt

ansible.cfg

[defaults]
inventory = inventory.gcp.yaml
host_key_checking = False
private_key_file = /Users/<your user>/.ssh/google_compute_engine
[inventory]
enable_plugins =  host_list, script, auto, yaml, ini, toml, gcp_compute

inventory.gcp.yaml

plugin: gcp_compute
projects:
  - gcp-project1
  - gcp-project2
auth_kind: serviceaccount
service_account_file: /Users/<your user>/.ssh/temp-serviceaccount.json

main.yaml

- name: echo
  hosts: all
  gather_facts: yes

  tasks:
  - name: Manage instances
    # connection: ssh
    shell: |
      server_name=`hostname`
      echo $server_name checking legacy-endpoint-access/0.1
      leg1=$(curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/legacy-endpoint-access/0.1)
      echo $leg1
      echo $server_name checking legacy-endpoint-access/v1beta1
      leg2=$(curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/legacy-endpoint-access/v1beta1)
      echo $leg2
    register: out
  - debug: var=out.stdout_lines

By default ansible will not use gcloud generated ssh key to connect to GCE instances. So you may need to do below.
"gcloud compute config-ssh" will add hostnames to your ~/.ssh/config and you can now more easily connect to gce instances and most importantly, you figure the compute key that ansible should use to connect to gce instances.
So in ansible.cfg, this line is crucial
"private_key_file = /Users//.ssh/google_compute_engine"

gcloud compute config-ssh --remove
gcloud compute config-ssh
ansible-playbook main.yaml

Now you can happily run "ansible-playbook main.yaml"


答:
Maybe this will be helpful:</p>

```<code>holidays = {'Autumn Half Term Holidays': ('16 Feb 2019', '25 Feb 2019')}
holidays_map = {date.date(): holiday for holiday, dates in holidays.items() for date in pd.date_range(*dates)}

df['holiday'] = df['datetime'].dt.date.map(holidays_map).fillna('Term time')

df

             datetime                    holiday
0 2019-02-15 13:00:00                  Term time
1 2019-02-15 14:00:00                  Term time
2 2019-02-15 15:00:00                  Term time
3 2019-02-15 16:00:00                  Term time
4 2019-02-16 17:00:00  Autumn Half Term Holidays
</code>```

Title: Create new column with categorical variables based on date range

Body:
Maybe this will be helpful:

holidays = {'Autumn Half Term Holidays': ('16 Feb 2019', '25 Feb 2019')}
holidays_map = {date.date(): holiday for holiday, dates in holidays.items() for date in pd.date_range(*dates)}

df['holiday'] = df['datetime'].dt.date.map(holidays_map).fillna('Term time')

df

             datetime                    holiday
0 2019-02-15 13:00:00                  Term time
1 2019-02-15 14:00:00                  Term time
2 2019-02-15 15:00:00                  Term time
3 2019-02-15 16:00:00                  Term time
4 2019-02-16 17:00:00  Autumn Half Term Holidays


问:
Converting SQL query to Spark Data-frame
I want to convert the below query's to a spark data frame (I am pretty new to spark):

-- Creating group number

```<code>select distinct *, DENSE_RANK() OVER(ORDER BY person_id, trust_id) AS group_number;
</code>```

-- This is what I got so far for above

```<code>df = self.spark.sql("select person_id, trust_id, insurance_id, amount, time_of_app, place_of_app from {}".format(self.tables['people']))

df = df.withColumn("group_number", dense_rank().over(Window.partitionBy("person_id", "trust_id").OrderBy("person_id", "trust_id")))
</code>```

-- Different query 1

```<code>where group_number in (select group_number from etl_table_people where code like 'H%') group by group_number having count(distinct amount) > 1;
</code>```

-- Different query 2

```<code>where insurance_id = 'V94.12'
group by group_number having count(distinct amount) = 2;
</code>```

答:
What you are looking for is Window Spec Function of spark.

```<code>val windowSpec = Window.partitionBy("person_id","trust_id").orderBy(col("person_id").desc).orderBy(col("trust_id").desc)

df.withColumn("group_number", dense_rank() over windowSpec)
</code>```

And you get your data frame using spark based on your Data Source. You can refer this if your source is Hive

Body:
I want to convert the below query's to a spark data frame (I am pretty new to spark):

-- Creating group number

select distinct *, DENSE_RANK() OVER(ORDER BY person_id, trust_id) AS group_number;

-- This is what I got so far for above

df = self.spark.sql("select person_id, trust_id, insurance_id, amount, time_of_app, place_of_app from {}".format(self.tables['people']))

df = df.withColumn("group_number", dense_rank().over(Window.partitionBy("person_id", "trust_id").OrderBy("person_id", "trust_id")))

-- Different query 1

where group_number in (select group_number from etl_table_people where code like 'H%') group by group_number having count(distinct amount) > 1;

-- Different query 2

where insurance_id = 'V94.12'
group by group_number having count(distinct amount) = 2;

Body:
What you are looking for is Window Spec Function of spark.

val windowSpec = Window.partitionBy("person_id","trust_id").orderBy(col("person_id").desc).orderBy(col("trust_id").desc)

df.withColumn("group_number", dense_rank() over windowSpec)

And you get your data frame using spark based on your Data Source. You can refer this if your source is Hive


问:
Keras TLSTM ext Classification differing train and test shape
I am working on a text classification problem in which I am feeding GloVe embeddings into an LSTM network. I have preprocessed the text and perform the following below:

```<code>max_features = 300
tokenizer = Tokenizer(num_words=max_features, split=' ')
tokenizer.fit_on_texts(train['text'].values)
train_f = tokenizer.texts_to_sequences(train['text'].values)
word_index = tokenizer.word_index #used for word embeddings
train_f = pad_sequences(train_f)
</code>```

The shape of train_f is: (25000, 1225). I then performed the same on the test set:

```<code>max_features = 300
tokenizer = Tokenizer(num_words=max_features, split=' ')
tokenizer.fit_on_texts(test['text'].values)
test_f = tokenizer.texts_to_sequences(test['text'].values)
test_f = pad_sequences(test_f)
</code>```

This resulted in a test shape of: (25000, 1223). When going ahead and loaded the embeddings in and fit the network. I am unable to predict on the testing set as I get the error:

```<code>ValueError: Error when checking input: expected embedding_2_input to have shape (1225,) but got array with shape (1223,)
</code>```

I cannot seem to spot my mistake. Any help would be much appreciated!

答:
I think that you have an error on the code of your test set :

```<code>tokenizer.fit_on_texts(test['text'].values)
test_f = tokenizer.texts_to_sequences(train['text'].values)
</code>```

should be :

```<code>tokenizer.fit_on_texts(test['text'].values)
test_f = tokenizer.texts_to_sequences(test['text'].values)
</code>```

Edit

It's looks like you just don't have the same test and train shape before your tokenize it.

Check the shape of your test['text'] and train['text']

Body:
I am working on a text classification problem in which I am feeding GloVe embeddings into an LSTM network. I have preprocessed the text and perform the following below:

max_features = 300
tokenizer = Tokenizer(num_words=max_features, split=' ')
tokenizer.fit_on_texts(train['text'].values)
train_f = tokenizer.texts_to_sequences(train['text'].values)
word_index = tokenizer.word_index #used for word embeddings
train_f = pad_sequences(train_f)

The shape of train_f is: (25000, 1225). I then performed the same on the test set:

max_features = 300
tokenizer = Tokenizer(num_words=max_features, split=' ')
tokenizer.fit_on_texts(test['text'].values)
test_f = tokenizer.texts_to_sequences(test['text'].values)
test_f = pad_sequences(test_f)

This resulted in a test shape of: (25000, 1223). When going ahead and loaded the embeddings in and fit the network. I am unable to predict on the testing set as I get the error:

ValueError: Error when checking input: expected embedding_2_input to have shape (1225,) but got array with shape (1223,)

I cannot seem to spot my mistake. Any help would be much appreciated!

Body:
I think that you have an error on the code of your test set :

tokenizer.fit_on_texts(test['text'].values)
test_f = tokenizer.texts_to_sequences(train['text'].values)

should be :

tokenizer.fit_on_texts(test['text'].values)
test_f = tokenizer.texts_to_sequences(test['text'].values)

Edit

It's looks like you just don't have the same test and train shape before your tokenize it.

Check the shape of your test['text'] and train['text']


问:
Database design for email-style application
I'm looking for some advice on how to design a database for an email-style application, specifically how to handle sending a message to multiple users, and displaying what messages were sent to what users.

This is what I have so far:

Messages (Primary Key is Id)

Id (Identity)

SenderId (Foreign Key to Users.Id)

<message data>

ReceivedMessages (Primary key is MessageId + RecipientId)

MessageId (Foreign Key to Messages.Id)

RecipientId (Foreign Key to Users.Id)

IsRead

So for every message sent, there would be one row in Messages, with the data, and then one row for each recipient in ReceivedMessages.

But what if I want to view all the messages sent by a user, and who they were sent to? For each message, I'd need to find all the ReceivedMessages rows for that message, and join all of those with the user table, and then somehow concat all the names (something like this: Concatenate many rows into a single text string?). Might this cause scaling issues, or is it not really anything to worry about?

Any thoughts/suggestions? Thanks.

答:
all the messages sent by a user, and who they were sent to

You can do it as an aggregate query, something like:

```<code>SELECT u1.user_name, m.message, GROUP_CONCAT(DISTINCT u2.user_name)
FROM messages m JOIN users u1 ON (m.senderID=u1.user_id)
                JOIN receivedmessages r ON (m.id=r.messageId)
                JOIN users u2 ON (r.RecipientId=u2.user_id)
GROUP BY u1.user_name, m.message;
</code>```

But because Recipients is essentially unlimited, you may run up against the string length limit on GROUP_CONCAT.

So it's likely better to do an unaggregated select and process the records for display in your application layer:

```<code>SELECT u1.user_name, m.message, DISTINCT u2.user_name
FROM messages m JOIN users u1 ON (m.senderID=u1.user_id)
                JOIN receivedmessages r ON (m.id=r.messageId)
                JOIN users u2 ON (r.RecipientId=u2.user_id)
ORDER BY u1.user_name, m.sent_date, u2.user_name;
</code>```

Body:
all the messages sent by a user, and who they were sent to

You can do it as an aggregate query, something like:

SELECT u1.user_name, m.message, GROUP_CONCAT(DISTINCT u2.user_name)
FROM messages m JOIN users u1 ON (m.senderID=u1.user_id)
                JOIN receivedmessages r ON (m.id=r.messageId)
                JOIN users u2 ON (r.RecipientId=u2.user_id)
GROUP BY u1.user_name, m.message;

But because Recipients is essentially unlimited, you may run up against the string length limit on GROUP_CONCAT.

So it's likely better to do an unaggregated select and process the records for display in your application layer:

SELECT u1.user_name, m.message, DISTINCT u2.user_name
FROM messages m JOIN users u1 ON (m.senderID=u1.user_id)
                JOIN receivedmessages r ON (m.id=r.messageId)
                JOIN users u2 ON (r.RecipientId=u2.user_id)
ORDER BY u1.user_name, m.sent_date, u2.user_name;


问:
how to generate code with ODL Yangtools maven plugin for yang-version 1.1 module
How to generate Java code from a yang-version 1.1 module with the OpenDaylight Yangtools maven plugin?

I have a yang-version 1.1 model (first part shown next)

```<code>module o-ran-sc-my-desc-v1 {
    yang-version 1.1;
    namespace "urn:o-ran:my-desc:1.0";
    prefix rxad;

    organization
        "O-RAN Software Community";
    contact
        "www.o-ran.org";
</code>```

I started with the YANG Tools guide https://wiki.opendaylight.org/view/YANG_Tools:User_Guide to construct a POM file and generate code. That has old versions tho and an invalid code generator class name.  I upgraded to plugin version 4.0.1, code generator version 3.0.9, both are the very latest in Maven central, and figured out the name of the code generator class. Finally got something working in maven but now I get this code generator error:

```<code>[ERROR] Failed to execute goal org.opendaylight.yangtools:yang-maven-plugin:4.0.1:generate-sources (default) on project o1-netconf-client:
Execution default of goal org.opendaylight.yangtools:yang-maven-plugin:4.0.1:generate-sources failed: An API incompatibility was
encountered while executing org.opendaylight.yangtools:yang-maven-plugin:4.0.1:generate-sources: java.lang.NoSuchMethodError:
org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils.getAllTypeDefinitions(Lorg/opendaylight/yangtools/yang/model/api/DataNodeContainer;)Ljava/util/Collection;

</code>```

Relevant portion of POM posted below for completeness.

```<code>            <plugin>
                <groupId>org.opendaylight.yangtools</groupId>
                <artifactId>yang-maven-plugin</artifactId>
                <version>4.0.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate-sources</goal>
                        </goals>
                        <configuration>
                            <!-- directory containing yang files to parse and generate code -->
                            <yangFilesRootDir>my/agent/yang</yangFilesRootDir>
                            <codeGenerators>
                                <generator>
                                    <codeGeneratorClass>
                                        org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl
                                    </codeGeneratorClass>
                                    <!-- directory into which generated files will be placed -->
                                    <outputBaseDir>
                                        target/generated-sources/sal
                                    </outputBaseDir>
                                </generator>
                            </codeGenerators>
                            <!-- if true, plugin will search for yang files also in dependent
                                projects -->
                            <inspectDependencies>true</inspectDependencies>
                        </configuration>
                    </execution>
                </executions>
               <dependencies>
                    <dependency>
                        <groupId>org.opendaylight.mdsal</groupId>
                        <artifactId>maven-sal-api-gen-plugin</artifactId>
                        <version>3.0.9</version>
                        <type>jar</type>
                    </dependency>
               </dependencies>
            </plugin>
</code>```

Is it possible that I am using incompatible versions?

答:
Found a solution for generating Java binding classes from a yang-version 1.1 model using Open Daylight:

Set parent pom to an Open Daylight file. The parent specifies compatible versions, defines the code generator, etc.

Put yang files in directory src/main/yang. Presence of that directory activates the required profile from #1.

The working POM appears below, it's absurdly short, hope this saves the next person some frustration.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.opendaylight.mdsal</groupId>
        <artifactId>binding-parent</artifactId>
        <version>5.0.9</version>
        <relativePath></relativePath>
    </parent>
    <groupId>org.your.group.id.goes.here</groupId>
    <artifactId>o1-netconf-client</artifactId>
    <packaging>jar</packaging>
    <name>Descriptive Name Goes Here</name>
    <version>0.0.1-SNAPSHOT</version>
</project>
</code>```

When I run "mvn install" the executed steps include generate source, test, package as a jar etc. This is the critical one:

```<code>[INFO] --- yang-maven-plugin:4.0.6:generate-sources (binding) @ o1-netconf-client ---
[INFO] yang-to-sources: Code generator instantiated from org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl
[INFO] yang-to-sources: Inspecting /Users/me/path/to/files/o1-netconf-client/src/main/yang
[INFO] yang-to-sources: Found 0 dependencies in 16.91 ms
[INFO] yang-to-sources: Project model files found: 2
[INFO] yang-to-sources: 2 YANG models processed in 174.2 ms
[INFO] yang-to-sources: Sources will be generated to /Users/me/path/to/files/o1-netconf-client/target/generated-sources/mdsal-binding
[INFO] Found 13 Binding types in 106.8 ms
[INFO] Generating 21 Binding source files into 8 directories
[INFO] yang-to-sources: Sources generated by org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl: 26 in 211.1 ms
</code>```

If you want to roll your own, pick compatible versions from here: https://docs.opendaylight.org/projects/integration-distribution/en/latest/platform-versions.html

Body:
How to generate Java code from a yang-version 1.1 module with the OpenDaylight Yangtools maven plugin?

I have a yang-version 1.1 model (first part shown next)

module o-ran-sc-my-desc-v1 {
    yang-version 1.1;
    namespace "urn:o-ran:my-desc:1.0";
    prefix rxad;

    organization
        "O-RAN Software Community";
    contact
        "www.o-ran.org";

I started with the YANG Tools guide https://wiki.opendaylight.org/view/YANG_Tools:User_Guide to construct a POM file and generate code. That has old versions tho and an invalid code generator class name.  I upgraded to plugin version 4.0.1, code generator version 3.0.9, both are the very latest in Maven central, and figured out the name of the code generator class. Finally got something working in maven but now I get this code generator error:

[ERROR] Failed to execute goal org.opendaylight.yangtools:yang-maven-plugin:4.0.1:generate-sources (default) on project o1-netconf-client:
Execution default of goal org.opendaylight.yangtools:yang-maven-plugin:4.0.1:generate-sources failed: An API incompatibility was
encountered while executing org.opendaylight.yangtools:yang-maven-plugin:4.0.1:generate-sources: java.lang.NoSuchMethodError:
org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils.getAllTypeDefinitions(Lorg/opendaylight/yangtools/yang/model/api/DataNodeContainer;)Ljava/util/Collection;

Relevant portion of POM posted below for completeness.

            <plugin>
                <groupId>org.opendaylight.yangtools</groupId>
                <artifactId>yang-maven-plugin</artifactId>
                <version>4.0.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate-sources</goal>
                        </goals>
                        <configuration>

                            <yangFilesRootDir>my/agent/yang</yangFilesRootDir>
                            <codeGenerators>
                                <generator>
                                    <codeGeneratorClass>
                                        org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl
                                    </codeGeneratorClass>

                                    <outputBaseDir>
                                        target/generated-sources/sal
                                    </outputBaseDir>
                                </generator>
                            </codeGenerators>

                            <inspectDependencies>true</inspectDependencies>
                        </configuration>
                    </execution>
                </executions>
               <dependencies>
                    <dependency>
                        <groupId>org.opendaylight.mdsal</groupId>
                        <artifactId>maven-sal-api-gen-plugin</artifactId>
                        <version>3.0.9</version>
                        <type>jar</type>
                    </dependency>
               </dependencies>
            </plugin>

Is it possible that I am using incompatible versions?

Body:
Found a solution for generating Java binding classes from a yang-version 1.1 model using Open Daylight:

Set parent pom to an Open Daylight file. The parent specifies compatible versions, defines the code generator, etc.

Put yang files in directory src/main/yang. Presence of that directory activates the required profile from #1.

The working POM appears below, it's absurdly short, hope this saves the next person some frustration.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.opendaylight.mdsal</groupId>
        <artifactId>binding-parent</artifactId>
        <version>5.0.9</version>
        <relativePath></relativePath>
    </parent>
    <groupId>org.your.group.id.goes.here</groupId>
    <artifactId>o1-netconf-client</artifactId>
    <packaging>jar</packaging>
    <name>Descriptive Name Goes Here</name>
    <version>0.0.1-SNAPSHOT</version>
</project>

When I run "mvn install" the executed steps include generate source, test, package as a jar etc. This is the critical one:

[INFO] --- yang-maven-plugin:4.0.6:generate-sources (binding) @ o1-netconf-client ---
[INFO] yang-to-sources: Code generator instantiated from org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl
[INFO] yang-to-sources: Inspecting /Users/me/path/to/files/o1-netconf-client/src/main/yang
[INFO] yang-to-sources: Found 0 dependencies in 16.91 ms
[INFO] yang-to-sources: Project model files found: 2
[INFO] yang-to-sources: 2 YANG models processed in 174.2 ms
[INFO] yang-to-sources: Sources will be generated to /Users/me/path/to/files/o1-netconf-client/target/generated-sources/mdsal-binding
[INFO] Found 13 Binding types in 106.8 ms
[INFO] Generating 21 Binding source files into 8 directories
[INFO] yang-to-sources: Sources generated by org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl: 26 in 211.1 ms

If you want to roll your own, pick compatible versions from here: https://docs.opendaylight.org/projects/integration-distribution/en/latest/platform-versions.html


问:
Basic problem with Custom transition using Navigation controller
In my work on an iOS multi-screen App, I am trying to get my first custom animated transaction to work. Instead of using standard animations when presenting a screen modal and fullscreen, I want to have a horizontal slide in animation.

I have made this work by overriding perform in UIStoryboardSegue, and make the animation and transaction be performed from here.

Overall, it works, except from one case, which is when a navigation controller embeds a view.

In that case, I have followed a tutorial showing precisely how custom transaction is achieved by implementing the UINavigationControllerDelegate protocol for the particular navigation controller.

```<code>import Foundation
import UIKit

class AnimatedNavigationController: UINavigationController, UINavigationControllerDelegate {

    override func viewDidLoad() {

        super.viewDidLoad()
        delegate = self
    }

    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationController.Operation,
                              from fromVC: UIViewController,
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {

        return NavigationControllerTransition()
    }
}
</code>```

Unfortunately the delegate, which should return an animation object:

navigationController(_:animationControllerFor:from:to:)

is never called, and that is my primary problem.

In the tutorial mentioned, a button is used to perform a call to the navigation controller that pushes the destination view with animation set to true:

navigationController.pushViewController(view, animated:true)

In my case, I suspect that the problem is that the navigation controller pushes the view without having the animation parameter set to true, and that explains why the transaction delegate is never called.

(a confirmation off this theory will of course help a bit).

Consequently, I have tried to implement a custom segue that presents the view by calling the push function with animation set to true.

Sadly, I have not been able to get this to work.

When the navigationController.pushViewController(view, animated:true) is called, it raises an exception saying that view has already been pushed.

I have tried a lot without any luck. Code looks like this:

```<code>class NavigationControllerSegue: UIStoryboardSegue {

    override func perform() {

        let navigationController = self.destination as! UINavigationController

        let view = navigationController.viewControllers.first!

        navigationController.pushViewController(view, animated: true)
    }
}
</code>```

答:
Hey first of all we are talking about two different animations... the first "UIStoryboardSegue" creates a custom subclass UIStoryboardSegue, and this is assigned to the following in question set an id to the following, below just call from the 'ViewController' a self.performSegue(withIdentifier: "YOUR-ID", sender: nil), Example of the subclass UIStoryboardSegue:

```<code>import UIKit
// Example =>
class ScaleSegue: UIStoryboardSegue {

    override func perform() {
        self.scale()
    }

    func scale() {
        let toViewController = self.destination
        let fromViewController = self.source

        let containerView = fromViewController.view.superview
        let originalCenter = fromViewController.view.center

        //let originalCenter = self.posizioneClick

        toViewController.view.transform = CGAffineTransform.init(scaleX: 0.05, y: 0.05)
        toViewController.view.center = originalCenter

        containerView?.addSubview(toViewController.view)

        UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut, animations: {
            toViewController.view.transform = CGAffineTransform.identity
        }, completion: { success in
            fromViewController.present(toViewController, animated: false, completion: nil)
        })
    }

}
</code>```

Now, you have to create a segue from storyboard and set as custom class of the segue from the AttributeInspector:

Now to use this you just need to call from the view controller => self.performSegue(withIdentifier: "segue1", sender: nil). Different is the way to implement Transition with UIViewControllerTransitioningDelegate.
If you need to let me know, I can give you examples using this technique too, so long.

Body:
In my work on an iOS multi-screen App, I am trying to get my first custom animated transaction to work. Instead of using standard animations when presenting a screen modal and fullscreen, I want to have a horizontal slide in animation.

I have made this work by overriding perform in UIStoryboardSegue, and make the animation and transaction be performed from here.

Overall, it works, except from one case, which is when a navigation controller embeds a view.

In that case, I have followed a tutorial showing precisely how custom transaction is achieved by implementing the UINavigationControllerDelegate protocol for the particular navigation controller.

import Foundation
import UIKit

class AnimatedNavigationController: UINavigationController, UINavigationControllerDelegate {

    override func viewDidLoad() {

        super.viewDidLoad()
        delegate = self
    }

    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationController.Operation,
                              from fromVC: UIViewController,
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {

        return NavigationControllerTransition()
    }
}

Unfortunately the delegate, which should return an animation object:

navigationController(_:animationControllerFor:from:to:)

is never called, and that is my primary problem.

In the tutorial mentioned, a button is used to perform a call to the navigation controller that pushes the destination view with animation set to true:

navigationController.pushViewController(view, animated:true)

In my case, I suspect that the problem is that the navigation controller pushes the view without having the animation parameter set to true, and that explains why the transaction delegate is never called.

(a confirmation off this theory will of course help a bit).

Consequently, I have tried to implement a custom segue that presents the view by calling the push function with animation set to true.

Sadly, I have not been able to get this to work.

When the navigationController.pushViewController(view, animated:true) is called, it raises an exception saying that view has already been pushed.

I have tried a lot without any luck. Code looks like this:

class NavigationControllerSegue: UIStoryboardSegue {

    override func perform() {

        let navigationController = self.destination as! UINavigationController

        let view = navigationController.viewControllers.first!

        navigationController.pushViewController(view, animated: true)
    }
}

Body:
Hey first of all we are talking about two different animations... the first "UIStoryboardSegue" creates a custom subclass UIStoryboardSegue, and this is assigned to the following in question set an id to the following, below just call from the 'ViewController' a self.performSegue(withIdentifier: "YOUR-ID", sender: nil), Example of the subclass UIStoryboardSegue:

import UIKit
// Example =>
class ScaleSegue: UIStoryboardSegue {

    override func perform() {
        self.scale()
    }

    func scale() {
        let toViewController = self.destination
        let fromViewController = self.source

        let containerView = fromViewController.view.superview
        let originalCenter = fromViewController.view.center

        //let originalCenter = self.posizioneClick

        toViewController.view.transform = CGAffineTransform.init(scaleX: 0.05, y: 0.05)
        toViewController.view.center = originalCenter

        containerView?.addSubview(toViewController.view)

        UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut, animations: {
            toViewController.view.transform = CGAffineTransform.identity
        }, completion: { success in
            fromViewController.present(toViewController, animated: false, completion: nil)
        })
    }

}

Now, you have to create a segue from storyboard and set as custom class of the segue from the AttributeInspector:

Now to use this you just need to call from the view controller => self.performSegue(withIdentifier: "segue1", sender: nil). Different is the way to implement Transition with UIViewControllerTransitioningDelegate.
If you need to let me know, I can give you examples using this technique too, so long.


问:
I install '@angular/cdk' and got an error when I import DragDropModule, what do I do wrong?
What are you trying to do?

I want to use @angular/cdk (source) to make a modal draggable as seen in their tutorial

Reproduction

npm i @angular/cdk

then when I import the module in my file xxx.module.ts :

import { DragDropModule } from '@angular/cdk/drag-drop';

I immediately obtain a list of error messages :

```<code>ERROR in node_modules/@angular/cdk/bidi/dir.d.ts(26,9): error TS1086: An accessor cannot be declared in an ambient context.
</code>```

Environment

Here is my package.json :

```<code>{
  "name": "libertchan",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~8.2.14",
    "@angular/cdk": "^9.0.0",
    "@angular/common": "~8.2.14",
    "@angular/compiler": "~8.2.14",
    "@angular/core": "~8.2.14",
    "@angular/forms": "~8.2.14",
    "@angular/platform-browser": "~8.2.14",
    "@angular/platform-browser-dynamic": "~8.2.14",
    "@angular/router": "~8.2.14",
    "@ng-bootstrap/ng-bootstrap": "^5.2.1",
    "bootstrap": "^4.4.1",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.19",
    "@angular/cli": "~8.3.19",
    "@angular/compiler-cli": "~8.2.14",
    "@angular/language-service": "~8.2.14",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  }
}
</code>```

答:
Found the answer : the problem was because I was using TypeScript 3.5 and the latest version of the CDK requires TypeScript 3.7.

Angular 8 can't use TypeScript 3.7 so I also needed to upgrade to Angular 9.

Body:
What are you trying to do?

I want to use @angular/cdk (source) to make a modal draggable as seen in their tutorial

Reproduction

npm i @angular/cdk

then when I import the module in my file xxx.module.ts :

import { DragDropModule } from '@angular/cdk/drag-drop';

I immediately obtain a list of error messages :

ERROR in node_modules/@angular/cdk/bidi/dir.d.ts(26,9): error TS1086: An accessor cannot be declared in an ambient context.

Environment

Here is my package.json :

{
  "name": "libertchan",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~8.2.14",
    "@angular/cdk": "^9.0.0",
    "@angular/common": "~8.2.14",
    "@angular/compiler": "~8.2.14",
    "@angular/core": "~8.2.14",
    "@angular/forms": "~8.2.14",
    "@angular/platform-browser": "~8.2.14",
    "@angular/platform-browser-dynamic": "~8.2.14",
    "@angular/router": "~8.2.14",
    "@ng-bootstrap/ng-bootstrap": "^5.2.1",
    "bootstrap": "^4.4.1",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.19",
    "@angular/cli": "~8.3.19",
    "@angular/compiler-cli": "~8.2.14",
    "@angular/language-service": "~8.2.14",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  }
}


问:
Tabulator 4.5 get data from api but do not render the table with data
In a modal context , Tabulator get data from api but do not render the table.

If I put a sleep of 500 milliseconds before return json from the api, the data show up.

```<code><div class="form-group">
 <div id="tablePersonnages"></div>
</div>

<script type="text/javascript">

var table = new Tabulator("#tablePersonnages",({
    pagination: "local",
    paginationSize: 10,
    history: true,
    ajaxURL: '@Url.Action("ObtenirPersonnages", "FicheHistorique")',
    ajaxParams: { idFiche: '@Model' },
    ajaxConfig: "POST",
    layout: "fitColumns",
    locale: true,
    langs: {
        "fr-fr": {

            "ajax": {
                "loading": "Chargement", //ajax loader text
                "error": "Erreur" //ajax error text
            },

            "pagination": {
                "first": "Début", //text for the first page button
                "first_title": "Première page", //tooltip text for the first page button
                "last": "Fin",
                "last_title": "Dernière page",
                "prev": "Préc",
                "prev_title": "Page précédente",
                "next": "Suiv",
                "next_title": "Page suivante"
            }
        }
    },
    columns: [ //Define Table Columns

        { title: "Id", field: "Id", visible: false },
        { title: "Nom", field: "Nom", headerFilter: "input", headerFilterPlaceholder: " " },
        { title: "Prenom", field: "Prenom", headerFilter: "input", headerFilterPlaceholder: " " },
        { title: "Fonction", field: "Fonction", headerFilter: "input", headerFilterPlaceholder: " " },
        { title: "Naissance", field: "Naissance" },
        { title: "Deces", field: "Deces" },
        { formatter: link, width: 10 }
    ]

}));
</code>```

答:
On Modal Open Event

Call table.redraw(true) If still doesn't work put the redraw in a setTimeout()


问:
Forcing NReco.ImageGenerator to download specific version of wkhtmltoimage.exe
I'm using NReco.ImageGenerator.dll v1.1.3. This component is very useful, but it downloads wkhtmltoimage.exe v0.12.4, and I need v0.12.5 instead.

How can I force it to download v0.12.5?

答:
I resolve my problem (create an image from HTML) with the following code:</p>

```<code>    public static void CreateImageFromHTML(string sourceHtml, string imageFileName, int width, int height)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.Width = width;
            webBrowser.Height = height;
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted += delegate (object sender, WebBrowserDocumentCompletedEventArgs e)
            {
                webBrowser_DocumentCompleted(sender, e, imageFileName);
            };

            webBrowser.DocumentText = sourceHtml;
            Application.Run();
            webBrowser = null;
            GC.Collect();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
        th.Join(4000);
    }

    static void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e, string fileName)
    {
        var webBrowser = (WebBrowser)sender;

        webBrowser.Dock = DockStyle.Fill;
        int height = webBrowser.Document.Body.ScrollRectangle.Height;
        int width= webBrowser.Document.Body.ScrollRectangle.Width;

        using (Bitmap bitmap = new Bitmap(width, height))
        {
            webBrowser.DrawToBitmap(bitmap, new Rectangle(0, 0, width, height));
            bitmap.Save(fileName, ImageFormat.Jpeg);
        }
    }
</code>```

Body:
I resolve my problem (create an image from HTML) with the following code:

    public static void CreateImageFromHTML(string sourceHtml, string imageFileName, int width, int height)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.Width = width;
            webBrowser.Height = height;
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted += delegate (object sender, WebBrowserDocumentCompletedEventArgs e)
            {
                webBrowser_DocumentCompleted(sender, e, imageFileName);
            };

            webBrowser.DocumentText = sourceHtml;
            Application.Run();
            webBrowser = null;
            GC.Collect();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
        th.Join(4000);
    }

    static void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e, string fileName)
    {
        var webBrowser = (WebBrowser)sender;

        webBrowser.Dock = DockStyle.Fill;
        int height = webBrowser.Document.Body.ScrollRectangle.Height;
        int width= webBrowser.Document.Body.ScrollRectangle.Width;

        using (Bitmap bitmap = new Bitmap(width, height))
        {
            webBrowser.DrawToBitmap(bitmap, new Rectangle(0, 0, width, height));
            bitmap.Save(fileName, ImageFormat.Jpeg);
        }
    }


问:
shape recognition on picture taken from webcam
i would like to extract information is there a human hand on some photo taken from local webcam.
I get how to extract light information, find brightest points or few of them, but how to recognize shape on some image?

I have started C# project, and I'm using AForge library to apply some filters to captured images, but I'm pretty stuck with shape recognition.

Where should I start?

答:
You can do this with OpenCV, using haar cascades.

There's even a classifier readily available for non-commercial use - see http://code.google.com/p/ehci/wiki/HandTracking

OwnerDisplayName: LILkillaBEE

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: diciu


问:
How to demonstrate the correctness of a program with a while cycle using Hoare's logic?
How can I demonstrate through Hoare logic the correctness of a program that has a while cycle. It would be fascinating that some one develop it with any example, due to as my problem to solve is:

Precondition={n>0}

```<code>cont := n;
sum := 0;
while cont <> 0 do:
    sum := sum + cont;
    cont := cont-1;
endwhile
</code>```

Postcondition={sum=1+2+...+n}

It is not necessary to develop this example. I just need to understand the procedure because I don't have a practical example. Thanks for your time.

答:
Hoare logic's "while" rule must be applied here:

If a command S satisfies a Hoare triple of the form {P ∧ B} S {P}, then the command while B do S satisfies {P} while B do S {P ∧ ¬B}.

This is the only technique for proving the postcondition of a while loop in Hoare logic, so you must apply it. The condition B and the loop body S are given in the code, but P can be any condition you choose so long as {P ∧ B} S {P} holds.

This Hoare triple asserts that if P is true before an iteration of the loop then it will still be true afterwards, so such a condition P is known as a loop invariant. To prove the postcondition of the loop you need to establish (1) that P is true before the first iteration of the loop, and (2) that P is preserved by the loop body.

The necessary invariant for the loop in your example is sum = n + (n-1) + ... + (cont+1), i.e. the sum of the numbers from cont+1 to n. In general, there is no systematic way to find the right loop invariant to use; you have to use your understanding of the algorithm, and your intuition/experience to come up with one yourself.

This is sufficient to show that if the loop terminates then its postcondition will be satisfied; you also need to establish that the loop does terminate. The technique you should apply here is to find a loop variant; this is usually some integer quantity which (1) decreases on each iteration of the loop, and (2) causes the loop to terminate when the quantity reaches zero.

In your example, cont is a loop variant, because the loop decrements cont := cont-1, and the loop condition terminates the loop when cont reaches zero. In general, like finding a useful invariant, there is no systematic procedure which finds a variant in all cases, but you can start by looking at the loop condition to see which variable(s) determine when the loop terminates.

Body:
How can I demonstrate through Hoare logic the correctness of a program that has a while cycle. It would be fascinating that some one develop it with any example, due to as my problem to solve is:

Precondition={n>0}

cont := n;
sum := 0;
while cont <> 0 do:
    sum := sum + cont;
    cont := cont-1;
endwhile

Postcondition={sum=1+2+...+n}

It is not necessary to develop this example. I just need to understand the procedure because I don't have a practical example. Thanks for your time.


问:
Regex to find a single character within a python list
I am trying to determine if a python list item has a single character in it and if so replace it with an uncontracted version. The issue I am facing is that I cannot get it to detect a single letter (X) without it converting say boxer -> bocrossbreeder

```<code>list = ['canine', 'dog', 'X', 'boxer', 'XBreed', ' x ']
list_trimmed = [re.sub(r'\040x\040', 'CrossBreed', lst) for lst in list]
</code>```

works okay for removing the ' x ' but if i try

```<code>list_trimmed = [re.sub(r'x', 'CrossBreed', lst) for lst in list]
</code>```

it creates boCrossBreeder as it detects the x in a word in the list item.

答:
You can use the beginning (^) and end of string ($) operators, like so:

```<code>list_strs = ['canine', 'dog', 'X', 'boxer', 'XBreed', ' x ']
list_trimmed = [re.sub(r'^X|x$', 'CrossBreed', lst) for lst in list_strs]
</code>```

Also, please note that list is a special word in Python, and you should avoid using it as a variable name.

I see another answer mentioning the word boundary operator (\b), but that does not correctly covers all scenarios, as the string 'canine X dog' will have its X replaced, while not being a single character string.

Body:
I am trying to determine if a python list item has a single character in it and if so replace it with an uncontracted version. The issue I am facing is that I cannot get it to detect a single letter (X) without it converting say boxer -> bocrossbreeder

list = ['canine', 'dog', 'X', 'boxer', 'XBreed', ' x ']
list_trimmed = [re.sub(r'\040x\040', 'CrossBreed', lst) for lst in list]

works okay for removing the ' x ' but if i try

list_trimmed = [re.sub(r'x', 'CrossBreed', lst) for lst in list]

it creates boCrossBreeder as it detects the x in a word in the list item.

Body:
You can use the beginning (^) and end of string ($) operators, like so:

list_strs = ['canine', 'dog', 'X', 'boxer', 'XBreed', ' x ']
list_trimmed = [re.sub(r'^X|x$', 'CrossBreed', lst) for lst in list_strs]

Also, please note that list is a special word in Python, and you should avoid using it as a variable name.

I see another answer mentioning the word boundary operator (\b), but that does not correctly covers all scenarios, as the string 'canine X dog' will have its X replaced, while not being a single character string.


问:
Authenticating to jenkins with python3 requests module
I have the following problem:

I get the status and some other information from a jenkins server via a curl right now and everything works fine and I get the information. Now I wanted to exchange
the way of how to get it to the requests lib and now I can not get to authentificate anymore. I use the following right now for the request part:

```<code>data ={"Username":"foo_user","Password":"bar_pass"}
response = session.post("jenkins_url_to_trigger",data=data )
</code>```

Also I tried to set the auth parameter with http basic auth.

If anyone was able to access a jenkins server via the requests lib it would be
nice to see a example of how to do it, since i'm stuck at it now for a while.

Also for the curl part which works I use the following simple syntax:

```<code>curl -u foo_user:bar_pass -X GET -H "Content-Type: application/json" jenkins_url/something/to/get/api/json --insecure
</code>```

Also I searched for similar questions and didn't find anything that did help me.

答:
Supply the credentials in a tuple as auth instead of in a dictionary as data.

```<code>credentials = ('foo_user', 'bar_pass')
response = session.post('<jenkins_url_to_trigger>', auth=credentials)
</code>```

See Authentication.

Body:
I have the following problem:

I get the status and some other information from a jenkins server via a curl right now and everything works fine and I get the information. Now I wanted to exchange
the way of how to get it to the requests lib and now I can not get to authentificate anymore. I use the following right now for the request part:

data ={"Username":"foo_user","Password":"bar_pass"}
response = session.post("jenkins_url_to_trigger",data=data )

Also I tried to set the auth parameter with http basic auth.

If anyone was able to access a jenkins server via the requests lib it would be
nice to see a example of how to do it, since i'm stuck at it now for a while.

Also for the curl part which works I use the following simple syntax:

curl -u foo_user:bar_pass -X GET -H "Content-Type: application/json" jenkins_url/something/to/get/api/json --insecure

Also I searched for similar questions and didn't find anything that did help me.

Body:
Supply the credentials in a tuple as auth instead of in a dictionary as data.

credentials = ('foo_user', 'bar_pass')
response = session.post('<jenkins_url_to_trigger>', auth=credentials)

See Authentication.


问:
Simple way to play a sound file (.aif)
I'm making an app for Mac OS X using Xcode, and I want it to play a alert sound when something happens.

What is the simplest code for playing a sound in Objective-C/Cocoa? Note that my sound file is an .aif.

Also, where do I put the sound file inside my project?

Thank you.

答:
For example, add the AudioToolbox framework, the add the sound file to your resources / project, then add the below to your .h:

```<code>#import <AudioToolbox/AudioToolbox.h>
</code>```

And then: (after @interface { blah } in your .h)

```<code>- (IBAction) playSound;
</code>```

Add the following to your .m: (change 'Ping' and 'wav' to the respective file name and type)

```<code>- (IBAction) playSound
{
    SystemSoundID soundID;
    NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"Ping" ofType:@"wav"];
    AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:soundFile], &soundID);
    AudioServicesPlaySystemSound(soundID);
    [soundFile release];
}
</code>```

Title: Simple way to play a sound file (.aif)

Body:
For example, add the AudioToolbox framework, the add the sound file to your resources / project, then add the below to your .h:

#import <AudioToolbox/AudioToolbox.h>

And then: (after @interface { blah } in your .h)

- (IBAction) playSound;

Add the following to your .m: (change 'Ping' and 'wav' to the respective file name and type)

- (IBAction) playSound
{
    SystemSoundID soundID;
    NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"Ping" ofType:@"wav"];
    AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:soundFile], &soundID);
    AudioServicesPlaySystemSound(soundID);
    [soundFile release];
}