问:
Get access to shared memory through semaphores
I have a different number of process which should write on the shared memory that I already defined. I'm trying by using system V semaphores. The semaphore (sem_access) is initialized at 1.

```<code>    sem_access.sem_op = -1;
    semop(sem_access_id, &sem_access, 1);

    info->index++;
    printf ("INDEX= %d\n", info->index);

    sem_access.sem_op = 1;
    semop(sem_access_id, &sem_access, 1);
</code>```

The problem is that the printf prints always the same number, without increment the index.
PS: Sorry for my bad english, but I'm spanish.
edit: if I insert a sleep(1) it works well, but i really I don't want the sleep!

答:
provide some more info about your code. What problem you are getting ? Does your process get stuck once resources acquired or not waiting ?

man page of semop() says :

1) If sem_op is less than zero, the process must have alter permission  on
       the  semaphore set. So if sem_access.sem_op = -1; when other process will make this value 0 or greater than 0 then only this process will access shared resources.

process 1 :
 sem_access.sem_op = -1; //this process will wait until condition not true

process 2: since in 1st process sem_op value is -1, this process needs to make sem_op value as 0 or 1 then only other process will get executed, So do like this

```<code>sem_access.sem_op = 1;
</code>```

as man page of semop() says, If sem_op is a positive integer, the operation adds this value  to  the
       semaphore  value  (semval). now sem_op becomes -1 + 1 = 0, refer again semop() man pages "This is a "wait-for-zero" operation: if semval is zero, the
       operation  can immediately proceed".

I hope you got some idea to resolve problem.

Body:
I have a different number of process which should write on the shared memory that I already defined. I'm trying by using system V semaphores. The semaphore (sem_access) is initialized at 1.

    sem_access.sem_op = -1;
    semop(sem_access_id, &sem_access, 1);

    info->index++;
    printf ("INDEX= %d\n", info->index);

    sem_access.sem_op = 1;
    semop(sem_access_id, &sem_access, 1);

The problem is that the printf prints always the same number, without increment the index.
PS: Sorry for my bad english, but I'm spanish.
edit: if I insert a sleep(1) it works well, but i really I don't want the sleep!

Body:
provide some more info about your code. What problem you are getting ? Does your process get stuck once resources acquired or not waiting ?

man page of semop() says :

1) If sem_op is less than zero, the process must have alter permission  on
       the  semaphore set. So if sem_access.sem_op = -1; when other process will make this value 0 or greater than 0 then only this process will access shared resources.

process 1 :
 sem_access.sem_op = -1; //this process will wait until condition not true

process 2: since in 1st process sem_op value is -1, this process needs to make sem_op value as 0 or 1 then only other process will get executed, So do like this

sem_access.sem_op = 1;

as man page of semop() says, If sem_op is a positive integer, the operation adds this value  to  the
       semaphore  value  (semval). now sem_op becomes -1 + 1 = 0, refer again semop() man pages "This is a "wait-for-zero" operation: if semval is zero, the
       operation  can immediately proceed".

I hope you got some idea to resolve problem.


来源: stackexchange

问:
How to convert std::string to QString preserving values and vice versa?
I am dealing with std::strings, in low level processing so I have to manipulate bits of characters of that string.

Also I have to show the results using GUI by viewing the result on QPlainTextEdit, as they may be copied for reverse processing.

so I deal with strings and results like 0xe3 may occur. and when I convert the std::string to QString to be shown in the GUI and vice versa. I use,

```<code> QString::fromStdString(myString); // to convert std::string to QString
 myQString.toStdString();          // to convert back from QString to std::string
</code>```

The problem is that when values result from processing on the string. after converting it to QString and try to
convert it back, values change.

I mean the value of each character,for example

0x3f becomes 0xbd, and 0xe3 becomes 0xef

I guess the problem happens due to encoding issues between std::string and QString, but I can not figure out how to deal with it or how to get the right values from QString.

答:
The source string is not valid UTF-8 and thus the roundtrip fails because the toStdString and fromStdString methods assume UTF-8. The Latin-1 roundtrip shouldn't fail and should simply map bytes 0-255 to Unicode C0 and C1. The code is a bit more verbose:

```<code>void test(const std::string & input) {
  auto latin_input = QByteArray::fromStdString(input);
  auto string = QString::fromLatin1(latin_input);
  auto latin_output = string.toLatin1();
  Q_ASSERT(latin_input == latin_output);
  auto output = latin_output.toStdString();
  Q_ASSERT(input == output);
}
</code>```

Note that many of the Latin-1 characters are not printable, so the QPlainTextEdit will not display them! To fix that, you'd need to create a custom translation table that provides a printable equivalent for every character code between 0 and 255.

ContentLicense: CC BY-SA 3.0

Body:
I am dealing with std::strings, in low level processing so I have to manipulate bits of characters of that string.

Also I have to show the results using GUI by viewing the result on QPlainTextEdit, as they may be copied for reverse processing.

so I deal with strings and results like 0xe3 may occur. and when I convert the std::string to QString to be shown in the GUI and vice versa. I use,

 QString::fromStdString(myString); // to convert std::string to QString
 myQString.toStdString();          // to convert back from QString to std::string

The problem is that when values result from processing on the string. after converting it to QString and try to
convert it back, values change.

I mean the value of each character,for example

0x3f becomes 0xbd, and 0xe3 becomes 0xef

I guess the problem happens due to encoding issues between std::string and QString, but I can not figure out how to deal with it or how to get the right values from QString.

Body:
The source string is not valid UTF-8 and thus the roundtrip fails because the toStdString and fromStdString methods assume UTF-8. The Latin-1 roundtrip shouldn't fail and should simply map bytes 0-255 to Unicode C0 and C1. The code is a bit more verbose:

void test(const std::string & input) {
  auto latin_input = QByteArray::fromStdString(input);
  auto string = QString::fromLatin1(latin_input);
  auto latin_output = string.toLatin1();
  Q_ASSERT(latin_input == latin_output);
  auto output = latin_output.toStdString();
  Q_ASSERT(input == output);
}

Note that many of the Latin-1 characters are not printable, so the QPlainTextEdit will not display them! To fix that, you'd need to create a custom translation table that provides a printable equivalent for every character code between 0 and 255.


问:
RabbitMQ and NiFi
I am new to NiFi, and advice welcomed.

We get data sent in from external sources in many small records. I am thinking of pulling those records into NiFi via RabbitMQ. I'd like to "spool" or "batch" those records up into larger grouping (perhaps based on some index in the records), and when a group of records reaches a certain size threshold write out to S3.

How to best accomplish this in NiFi? Any other suggestions?

Thanks, Gary

答: This should be achievable... I don't know that much about RabbitMQ, but assuming that it supports a JMS interface, then you could probably use NiFi's ConsumeJMS processor, followed by MergeContent to merge until your threshold is reached, and then PutS3Object to write to S3.</p>

Title: RabbitMQ and NiFi


问:
python version 3.6.3 Functions and lists
I am trying to run the following:

```<code>def count_small(numbers):
total = 0
for n in numbers:
    if n < 10:
        total = total + 1
    return total

lotto = [4, 8, 15, 16, 23, 42]
small = count_small(lotto)
print(small)
</code>```

Here I have defined a function 'count_small(numbers)'
it starts with a total of 0,
then checks each item in the list, to check that it is less than 10, if the item is less then 10, then 1 will be added to the total. I am running the function on the list 'lotto', as you can see 'lotto' has two numbers less than 10 '4' and '8' hence it should return 2, however, when I run the code it returns 1 instead.

答: Your indentation is incorrect. Place the return statement outside of your for loop.</p>

Body:
I am trying to run the following:

def count_small(numbers):
total = 0
for n in numbers:
    if n < 10:
        total = total + 1
    return total

lotto = [4, 8, 15, 16, 23, 42]
small = count_small(lotto)
print(small)

Here I have defined a function 'count_small(numbers)'
it starts with a total of 0,
then checks each item in the list, to check that it is less than 10, if the item is less then 10, then 1 will be added to the total. I am running the function on the list 'lotto', as you can see 'lotto' has two numbers less than 10 '4' and '8' hence it should return 2, however, when I run the code it returns 1 instead.


问:
scipy.optimize.minimize does not update weight parameters
Below is the code that I used to update the beta vector. It is randomly initialized. However, after several iterations, the beta vector is not updated. The cost does not decrease as well. Did I miss anything?

```<code>def objective_func(beta, features, spread, target):
    res = 0
    for i, feats in enumerate(features):
        W = feats.dot(beta)  # Series
        weighted_spread = W * spread[i]  # Series
        normalization = weighted_spread.sum()
        res += (target[i] - (weighted_spread / normalization).sum()) ** 2
    print(res)  # It always prints the same value
    return res

initial_beta = np.array([random() for _ in range(features[0].shape[1])])
print(initial_beta)
res = optimize.minimize(objective_func, x0=initial_beta,
                        args=(list(compress(features, training_mask)),
                              list(compress(spread, training_mask)),
                              list(compress(target, training_mask))),
                        method='L-BFGS-B',
                        callback=True)
print(initial_beta)
print(res.x)
print(res.success)
print(res.status)
print(res.message)
print(res.nit)
</code>```

The console:

```<code>[ 0.03935521  0.45679144  0.45673816  0.56107001]  # initial_beta before minimizing
228.625  # res
228.625
228.625
228.625
228.625
[ 0.03935521  0.45679144  0.45673816  0.56107001]  # initial_beta after minimizing
[ 0.03935521  0.45679144  0.45673816  0.56107001]  # res.x
True  # res.success
0  # res.status
b'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'  # res.message
0  # res.nit
</code>```

答: I just figure it out that normalization = weighted_spread.sum() should be normalization = W.sum() . Mathematical problem.

Body:
Below is the code that I used to update the beta vector. It is randomly initialized. However, after several iterations, the beta vector is not updated. The cost does not decrease as well. Did I miss anything?

def objective_func(beta, features, spread, target):
    res = 0
    for i, feats in enumerate(features):
        W = feats.dot(beta)  # Series
        weighted_spread = W * spread[i]  # Series
        normalization = weighted_spread.sum()
        res += (target[i] - (weighted_spread / normalization).sum()) ** 2
    print(res)  # It always prints the same value
    return res

initial_beta = np.array([random() for _ in range(features[0].shape[1])])
print(initial_beta)
res = optimize.minimize(objective_func, x0=initial_beta,
                        args=(list(compress(features, training_mask)),
                              list(compress(spread, training_mask)),
                              list(compress(target, training_mask))),
                        method='L-BFGS-B',
                        callback=True)
print(initial_beta)
print(res.x)
print(res.success)
print(res.status)
print(res.message)
print(res.nit)

The console:

[ 0.03935521  0.45679144  0.45673816  0.56107001]  # initial_beta before minimizing
228.625  # res
228.625
228.625
228.625
228.625
[ 0.03935521  0.45679144  0.45673816  0.56107001]  # initial_beta after minimizing
[ 0.03935521  0.45679144  0.45673816  0.56107001]  # res.x
True  # res.success
0  # res.status
b'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'  # res.message
0  # res.nit


问:
firebase.json for cloud function configuration?
My Firebase project uses several different storage buckets used by cloud function storage triggers. Although I can change the default bucket for a particular cloud storage function in the console or using CLI after deploying it, I was wondering if there was a way to configure these settings (bucket, memory limit, zip-deployment location) in firebase.json and pick them up automatically during deploy. Sometimes deployment of the entire project resets the cloud function settings, which causes issues for our users. Thanks!</p>

答:
If you want to configure values to consume in your functions, use environment configuration.

From the CLI:

```<code>firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"
</code>```

Then in a function:

```<code>functions.config().someservice.key
</code>```

Body:
If you want to configure values to consume in your functions, use environment configuration.

From the CLI:

firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"

Then in a function:

functions.config().someservice.key


问:
How to break span-element inline-block over row inside container?
I have the following HTML code:

```<code><span class="container">

    <span id="item1" class="item">
        <button class="removeitem"></button>
        <span class="text"></span>
    </span>

    <span id="item2" class="item">
        <button class="removeitem"></button>
        <span class="text"></span>
    </span>

    <span id="item3" class="item">
        <button class="removeitem"></button>
        <span class="text"></span>
    </span>

</span>
</code>```

Imagine the #item3 extends .container, but overflow is hidden. How can I achieve that the elements inside are still visible and will continue in the following row?

I tried the following (in Sass-syntax):

```<code>.container
    display: flex
    justify-content: flex-start
    flex-wrap: wrap
</code>```

But #item3 will just appear on the next row.

I tried making everything display: inline, but then I can not assign any height-properties.

I attached an image of what I want to achieve.

This is what the layout should look like. #item3 continues in the next row:

答:
What you are asking is not technically possible unless you use the natural wrapping of text as in this example:

```<code>.item {
  display: inline;
  background: yellow;
  margin-right: 5px;
  border: 2px solid green;
  line-height: 2;
}
</code>```

Fiddle:
https://jsfiddle.net/658tdurx/1/

ContentLicense: CC BY-SA 4.0

Body:
I have the following HTML code:

        <button class="removeitem"></button>

        <button class="removeitem"></button>

        <button class="removeitem"></button>

Imagine the #item3 extends .container, but overflow is hidden. How can I achieve that the elements inside are still visible and will continue in the following row?

I tried the following (in Sass-syntax):

.container
    display: flex
    justify-content: flex-start
    flex-wrap: wrap

But #item3 will just appear on the next row.

I tried making everything display: inline, but then I can not assign any height-properties.

I attached an image of what I want to achieve.

This is what the layout should look like. #item3 continues in the next row:

Body:
What you are asking is not technically possible unless you use the natural wrapping of text as in this example:

.item {
  display: inline;
  background: yellow;
  margin-right: 5px;
  border: 2px solid green;
  line-height: 2;
}

Fiddle:
https://jsfiddle.net/658tdurx/1/


问:
How to create dynamic hystrixcommand threadPoolKey
I am using hystrix for implementing circuit breaker concept in my springboot service. The HystrixCommand annotation that I use on the method that needs to be throttle the external service calls in case of threshhold number of failures is as follows:

```<code> @HystrixCommand(commandKey = "myCommandKey",
            groupKey = "myGroupKey",
            threadPoolKey = "myThreadPoolKey")
    public String myHystrixMethod(String someParam) { ....}
</code>```

Now, the service where myHystrixMethod resides is called by different clients. Based on the type of client that invokes the service, there is a logic to call a backend service designated for that particular client.

What I would like to do is to register all the threads (requests) invoked by a specific client in it's own hystrix threadpool. Which means, requests from client A would get registered in hystrix threadpool for client A and for client B in a hystrix threadpool for client B only. This would ensure that client B's requests to my service aren't throttled due to failures in client A.

For this, I can create separate service methods (one shown above) for every client and name the hystrix thread pool accordingly. However, with this approach, whenever there is a new client, i'll have to modify the source code to add it's service method.

Is there a way I can dynamically create the options inside of @HystrixCommand annotation based on a parameter, which is client ID in this case ?

答:
I don't know any way to do it with Hystrix library, but since you've asked for any other circuit breaker implementation that can do it, here is solution based on Resilience4J library.

In your application context you can register CircuitBreakerRegistry bean with default configuration for your clients.

```<code>@Bean
public CircuitBreakerRegistry circuitBreakerRegistry() {
    CircuitBreakerConfig config = CircuitBreakerConfig.custom()
            .failureRateThreshold(35)
            .ringBufferSizeInClosedState(1000)
            .ringBufferSizeInHalfOpenState(100)
            .waitDurationInOpenState(Duration.ofMinutes(1))
            .build();
    return CircuitBreakerRegistry.of(config);
}
</code>```

Then you simply inject this registry to your service and inside your protected method you can get CB for any client you need.

```<code>CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("ClientA");
</code>```

This operation will find already registered circuit breaker or create new one if necessary using registry default config.

And now you can use any CircuitBreaker method of choice: isCallPermitted() or executeRunnable() or any other.

For more information take a look at User Guide.

Body:
I am using hystrix for implementing circuit breaker concept in my springboot service. The HystrixCommand annotation that I use on the method that needs to be throttle the external service calls in case of threshhold number of failures is as follows:

 @HystrixCommand(commandKey = "myCommandKey",
            groupKey = "myGroupKey",
            threadPoolKey = "myThreadPoolKey")
    public String myHystrixMethod(String someParam) { ....}

Now, the service where myHystrixMethod resides is called by different clients. Based on the type of client that invokes the service, there is a logic to call a backend service designated for that particular client.

What I would like to do is to register all the threads (requests) invoked by a specific client in it's own hystrix threadpool. Which means, requests from client A would get registered in hystrix threadpool for client A and for client B in a hystrix threadpool for client B only. This would ensure that client B's requests to my service aren't throttled due to failures in client A.

For this, I can create separate service methods (one shown above) for every client and name the hystrix thread pool accordingly. However, with this approach, whenever there is a new client, i'll have to modify the source code to add it's service method.

Is there a way I can dynamically create the options inside of @HystrixCommand annotation based on a parameter, which is client ID in this case ?

Body:
I don't know any way to do it with Hystrix library, but since you've asked for any other circuit breaker implementation that can do it, here is solution based on Resilience4J library.

In your application context you can register CircuitBreakerRegistry bean with default configuration for your clients.

@Bean
public CircuitBreakerRegistry circuitBreakerRegistry() {
    CircuitBreakerConfig config = CircuitBreakerConfig.custom()
            .failureRateThreshold(35)
            .ringBufferSizeInClosedState(1000)
            .ringBufferSizeInHalfOpenState(100)
            .waitDurationInOpenState(Duration.ofMinutes(1))
            .build();
    return CircuitBreakerRegistry.of(config);
}

Then you simply inject this registry to your service and inside your protected method you can get CB for any client you need.

CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("ClientA");

This operation will find already registered circuit breaker or create new one if necessary using registry default config.

And now you can use any CircuitBreaker method of choice: isCallPermitted() or executeRunnable() or any other.

For more information take a look at User Guide.


问:
Generating an unordered list with jQuery
There is unordered list, which not works properly in IE6-7, I would like want to replace it by a jQuery function.

So, we have:

simple list with special #id (ul id="")

some
 tags

some special tag in
 to show the number of a row (or something else, as you wish).

I need a function which will give an unique number for each row, from the beginning to the end of our unordered list. (ul)

答:
Referring to this post Generating an unordered list with jQuery

Is there a way to start count all over again for another list using ul?
With the code above this is what i get!

 test

 test

 test

Output

1. test

2. test

3. test

second ul list

 test

 test

 test

Output

4. test

5. test

6. test

Instead of starting the second ul tag with 1. 2. 3. it continues to count using the first ul 5. 6. 7.

So is it possible to reset the count and star it all over again for another ul tag?

ContentLicense: CC BY-SA 2.5

Body:
Referring to this post Generating an unordered list with jQuery

Is there a way to start count all over again for another list using ul?
With the code above this is what i get!
<ul>
<li> test
<li> test
<li> test
<ul/>

Output

1. test

2. test

3. test

second ul list

<ul>
<li> test
<li> test
<li> test
<ul/>

Output

4. test

5. test

6. test

Instead of starting the second ul tag with 1. 2. 3. it continues to count using the first ul 5. 6. 7.

So is it possible to reset the count and star it all over again for another ul tag?


问:
Switching JPanels moves content diagonally
I have btnShowLibrary, which shows the books kept in the library. And then I have a button btnReturn that recreates previous JPanel with the btnShowLibrary among them.

Initializing contentPane:

```<code>setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new MigLayout("", "[124px,grow,fill][124px,grow,fill][124px,grow,fill]", "[30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill]"));
</code>```

btnShowLibrary:

```<code>JButton btnShowLibrary = new JButton("Show Library");
btnShowLibrary.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        contentPane.removeAll();
        contentPane.add(new ShowLibrary().getPane());
        contentPane.updateUI();
    }
});
contentPane.add(btnShowLibrary, "cell 1 5");
</code>```

ShowLibrary contentPane:

```<code>contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new MigLayout("", "[grow]", "[grow,fill][grow][]"));
</code>```

btnReturn:

```<code>Button btnReturn = new JButton("Return");
btnReturn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        contentPane.removeAll();
        contentPane.add(new Library().getPane());
        contentPane.updateUI();
    }
});
contentPane.add(btnReturn, "cell 0 1,alignx center,aligny bottom");
</code>```

Now for what happens:

Initialization

First click on the btnShowLibrary

First click on the btnReturn

2nd click on the bSL

2nd click on the bR

3rd click on the bSL

3rd click on the bR

From the pictures you can so how it's "moving" and I have no idea why. Can someone explain why this happens and suggest how to fix it?

答:
An easy way to manage multiple panels is with the CardLayout layout. This layout allows you to show one of a number of panels at a time, making it easy to move from one to the other in a window.  Here is a demo with some events passing between the GUI panels and the main "controller".  Ideally, the GUI classes would be in their own files.  See also https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html.</p>

```<code>package Q47644243;

import java.awt.AWTEvent;
import java.awt.CardLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsConfiguration;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

/**
 * Demonstrate multiple panels in a window using CardLayout
 *
 */
@SuppressWarnings("serial")
public class MultiplePanels extends JFrame implements VetoableChangeListener {

    public static void main(String[] args) {
        new MultiplePanels();
    }

    // GUI components
    private MainMenuPanel mainMenuPanel = null;
    private DataEntryPanel dataEntryPanel = null;
    private JPanel contentPanel;
    private CardLayout cardLayout = new CardLayout();

    final static String MENUPANEL = "Main Menu";
    final static String DATAPANEL = "Enter Data";

    // State variables
    private int m_data = 0;

    public MultiplePanels() {

        try {
            // Initialize
            jbInit();
        } catch(Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        try {
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            showCenterScreen(this);
            setCursor(Cursor.getDefaultCursor());
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void jbInit() {

        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create the GUI panels
        mainMenuPanel = new MainMenuPanel();
        dataEntryPanel = new DataEntryPanel();

        // Use property changes to communicate with the GUI
        addPropertyChangeListener(DataEntryPanel.PROPERTY_Data, dataEntryPanel);

        // Use vetoable changes to listen to the GUI
        mainMenuPanel.addVetoableChangeListener(this);
        dataEntryPanel.addVetoableChangeListener(this);

        this.setTitle("Multiple Panes Example");
        cardLayout.setHgap(5);
        cardLayout.setVgap(5);

        // Add the panels
        contentPanel = (JPanel) this.getContentPane();
        contentPanel.setLayout(cardLayout);
        contentPanel.add(mainMenuPanel, MENUPANEL);
        contentPanel.add(dataEntryPanel, DATAPANEL);

        // Bring the menu to the front
        cardLayout.show(contentPanel, MENUPANEL);
    }

    /**
     * Receive events from the GUI and process them. There are two expected:<br>
     * <ol>
     * <li>a change to the total seconds field. This is validated and accepted or vetoed
     * if the new value is not an integer >=0; and <br>
     * <li>a request to perform the calculation.
     * </ol>
     */
    @Override
    public void vetoableChange(PropertyChangeEvent pce)
            throws PropertyVetoException {

        // The GUI is signaling a change that the "controller/model" needs
        // to deal with
        if (DataEntryPanel.PROPERTY_Data.equals(pce.getPropertyName())) {
            // Test to see if the data is valid
            int newData = 1;
            try {
                     newData = Integer.parseInt((String) pce.getNewValue());
            } catch (NumberFormatException e) {
                newData = -1;
            }
            if (newData <= 0) {
                // Signals the GUI to reject the entered value.
                throw new PropertyVetoException("Please enter a valid integer that is greater than zero.", pce);
            }
            // Save the state or data - bind with a database or
            // some other action.  Here we'll just update a "state" variable
            m_data = newData;
        }

        // Data entry completed - validate and switch back to main menu
        if (DataEntryPanel.PROPERTY_Done.equals(pce.getPropertyName())) {
            if (m_data <= 0) {
                // Request better data
                throw new PropertyVetoException("Please enter a valid integer that is greater than zero.", pce);
            }
            // Switch back to the Main menu
            cardLayout.show(contentPanel, MENUPANEL);
        }

        // Button pressed on the main menu
        if (MainMenuPanel.PROPERTY_MenuButton.equals(pce.getPropertyName())) {
            // This is a command to do something.  Using a vetoable change event
            // provides a nice mechanism to pass a message back to the GUI
            // if required.
            cardLayout.show(contentPanel, DATAPANEL);
        }
    }

    /**
     *  Show in the center of the screen.
     *  (pack, set location and set visibility)
     *  @param window Window to position
     */
    private void showCenterScreen(Window window) {
        positionScreen (window);
        window.setVisible(true);
        window.toFront();
    }   //  showCenterScreen

    /**
     *  Position window in center of the screen
     *  @param window Window to position
     */
    private void positionScreen (Window window)
    {
        window.pack();
        // take into account task bar and other adornments
        GraphicsConfiguration config = window.getGraphicsConfiguration();
        Rectangle bounds = config.getBounds();
        Dimension sSize = bounds.getSize();
        Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(config);
        sSize.width -= (insets.left + insets.right);
        sSize.height -= (insets.top + insets.bottom);

        Dimension wSize = window.getSize();
        //  fit on window
        if (wSize.height > sSize.height)
            wSize.height = sSize.height;
        if (wSize.width > sSize.width)
            wSize.width = sSize.width;
        window.setSize(wSize);
        //  Center
        int x = (sSize.width - wSize.width) / 2;
        int y = (sSize.height - wSize.height) / 2;
        //
        window.setLocation(bounds.x + x + insets.left, bounds.y + y + insets.top);
    }   //  positionScreen

/*****************************************************************************/

    /**
     * A simple demo GUI for the a main menu with a button.  This should be in its own file
     * but for stack overflow, its presented as a subclass.
     *
     */
    public class MainMenuPanel extends JPanel implements ActionListener, PropertyChangeListener {

        /**
         *  Constructor
         */
        public MainMenuPanel () {

            try {
                jbInit();
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        public final static String PROPERTY_MenuButton = "MenuButton";

        private GridBagLayout gridBagLayout = new GridBagLayout();

        private JLabel      lTitle = new JLabel();
        private JButton     bOption1 = new JButton();

        private void jbInit() {

            setLayout(gridBagLayout);

            // Label
            lTitle.setToolTipText("Click a Menu Button");
            lTitle.setText("Main Menu");

            // Menu Button
            bOption1.setToolTipText("Show the Data Entry Panel");
            bOption1.setText("Enter Data");
            bOption1.addActionListener(this);

            // Layout the fields
            this.add(lTitle,    new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
                ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 2, 5), 0, 0));

            this.add(bOption1,      new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
                ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0));

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == bOption1) {
                try {
                    fireVetoableChange(PROPERTY_MenuButton,0,1);
                } catch (PropertyVetoException e1) {
                    e1.printStackTrace();
                }
            }
        }

        // Property Change receives events from the controller
        // Doesn't do anything in this case but could be used to
        // change the menu based on state, show different entries
        // etc...
        @Override
        public void propertyChange(PropertyChangeEvent pce) {
            /* Example
            if (PROPERTY_APropertyName.equals(pce.getPropertyName())) {
                // do something relevant
            }
            */
        }
    }

/*****************************************************************************/

    /**
     * A simple demo GUI for the a data entry with a button.  This should be in its own file
     * but for stack overflow, its presented as a subclass.
     *
     */
    public class DataEntryPanel extends JPanel implements ActionListener, PropertyChangeListener {

        /**
         *  Constructor
         */
        public DataEntryPanel () {

            try {
                jbInit();
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        // Property definitions
        public final static String PROPERTY_Done = "DoneButton";
        public final static String PROPERTY_Data = "myData";

        private GridBagLayout gridBagLayout = new GridBagLayout();

        private JLabel              lData = new JLabel();
        private JFormattedTextField fData = new JFormattedTextField("0");
        private JButton             bDone = new JButton();

        private String lastGoodData = "0";
        private boolean m_settingValue;

        private void jbInit() {

            setLayout(gridBagLayout);

            // Label
            lData.setToolTipText("Enter a positive integer");
            lData.setText("Enter number:");

            // Field
            fData.setText(lastGoodData);
            fData.setEditable(true);
            fData.setHorizontalAlignment(SwingConstants.RIGHT);
            fData.addPropertyChangeListener("value", this);
            fData.setColumns(15);

            // Button
            bDone.setToolTipText("Save the data and return to the menu.");
            bDone.setText("Save/Done");
            bDone.addActionListener(this);

            // Layout the fields
            this.add(lData,    new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
                ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
            this.add(fData,    new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
                    ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));

            //grab extra space when window is maximized
            JPanel filler = new JPanel();
            filler.setOpaque(false);
            filler.setBorder(null);
            this.add(filler,        new GridBagConstraints(0, 1, 1, 1, 0.0, 1.0
                    ,GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));

            this.add(bDone,        new GridBagConstraints(1, 2, 2, 1, 0.0, 0.0
                ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(15, 5, 10, 5), 0, 0));

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // Ignore button events while a field is setting its value
            // This can happen if the field focus is lost to a button click
            if (e.getSource() == bDone && !m_settingValue) {
                try {
                    fireVetoableChange(PROPERTY_Done,0,1);
                } catch (PropertyVetoException pve) {
                    JOptionPane.showMessageDialog(null,
                              pve.getMessage(), "Error Massage",
                              JOptionPane.ERROR_MESSAGE);
                }
            }
        }

        // Property Change receives events from the controller or fields
        @Override
        public void propertyChange(PropertyChangeEvent pce) {

            m_settingValue = true;
            // The "value" property signals a change in a field value
            // Send the new value to the controller/model for validation
            if (fData.equals(pce.getSource()) && "value".equals(pce.getPropertyName())) {
                // Record the old value in case the change is vetoed. Don't use
                // the pce.getOldValue(), it isn't always accurate.
                String oldValue = lastGoodData;
                String newValue = (String) pce.getNewValue();

                try {
                    fireVetoableChange(PROPERTY_Data, oldValue, newValue);
                    lastGoodData = newValue;
                } catch (PropertyVetoException e) {
                    JOptionPane.showMessageDialog(null,
                              e.getMessage(), "Error Massage",
                              JOptionPane.ERROR_MESSAGE);
                    // Reset fData outside of the "value" event thread/loop
                    // Otherwise the value is not updated to the oldValue
                    EventQueue.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            fData.setText(lastGoodData);
                        }
                    });
                }
                m_settingValue = false;
            }
        }
    }
}
</code>```

Body:
I have btnShowLibrary, which shows the books kept in the library. And then I have a button btnReturn that recreates previous JPanel with the btnShowLibrary among them.

Initializing contentPane:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new MigLayout("", "[124px,grow,fill][124px,grow,fill][124px,grow,fill]", "[30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill][30px,grow,fill]"));

btnShowLibrary:

JButton btnShowLibrary = new JButton("Show Library");
btnShowLibrary.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        contentPane.removeAll();
        contentPane.add(new ShowLibrary().getPane());
        contentPane.updateUI();
    }
});
contentPane.add(btnShowLibrary, "cell 1 5");

ShowLibrary contentPane:

contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new MigLayout("", "[grow]", "[grow,fill][grow][]"));

btnReturn:

Button btnReturn = new JButton("Return");
btnReturn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        contentPane.removeAll();
        contentPane.add(new Library().getPane());
        contentPane.updateUI();
    }
});
contentPane.add(btnReturn, "cell 0 1,alignx center,aligny bottom");

Now for what happens:

Initialization

First click on the btnShowLibrary

First click on the btnReturn

2nd click on the bSL

2nd click on the bR

3rd click on the bSL

3rd click on the bR

From the pictures you can so how it's "moving" and I have no idea why. Can someone explain why this happens and suggest how to fix it?

Body:
An easy way to manage multiple panels is with the CardLayout layout. This layout allows you to show one of a number of panels at a time, making it easy to move from one to the other in a window.  Here is a demo with some events passing between the GUI panels and the main "controller".  Ideally, the GUI classes would be in their own files.  See also https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html.

package Q47644243;

import java.awt.AWTEvent;
import java.awt.CardLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsConfiguration;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

/**
 * Demonstrate multiple panels in a window using CardLayout
 *
 */
@SuppressWarnings("serial")
public class MultiplePanels extends JFrame implements VetoableChangeListener {

    public static void main(String[] args) {
        new MultiplePanels();
    }

    // GUI components
    private MainMenuPanel mainMenuPanel = null;
    private DataEntryPanel dataEntryPanel = null;
    private JPanel contentPanel;
    private CardLayout cardLayout = new CardLayout();

    final static String MENUPANEL = "Main Menu";
    final static String DATAPANEL = "Enter Data";

    // State variables
    private int m_data = 0;

    public MultiplePanels() {

        try {
            // Initialize
            jbInit();
        } catch(Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        try {
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            showCenterScreen(this);
            setCursor(Cursor.getDefaultCursor());
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void jbInit() {

        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create the GUI panels
        mainMenuPanel = new MainMenuPanel();
        dataEntryPanel = new DataEntryPanel();

        // Use property changes to communicate with the GUI
        addPropertyChangeListener(DataEntryPanel.PROPERTY_Data, dataEntryPanel);

        // Use vetoable changes to listen to the GUI
        mainMenuPanel.addVetoableChangeListener(this);
        dataEntryPanel.addVetoableChangeListener(this);

        this.setTitle("Multiple Panes Example");
        cardLayout.setHgap(5);
        cardLayout.setVgap(5);

        // Add the panels
        contentPanel = (JPanel) this.getContentPane();
        contentPanel.setLayout(cardLayout);
        contentPanel.add(mainMenuPanel, MENUPANEL);
        contentPanel.add(dataEntryPanel, DATAPANEL);

        // Bring the menu to the front
        cardLayout.show(contentPanel, MENUPANEL);
    }

    /**
     * Receive events from the GUI and process them. There are two expected:<br>
     * <ol>
     * <li>a change to the total seconds field. This is validated and accepted or vetoed
     * if the new value is not an integer >=0; and <br>
     * <li>a request to perform the calculation.
     * </ol>
     */
    @Override
    public void vetoableChange(PropertyChangeEvent pce)
            throws PropertyVetoException {

        // The GUI is signaling a change that the "controller/model" needs
        // to deal with
        if (DataEntryPanel.PROPERTY_Data.equals(pce.getPropertyName())) {
            // Test to see if the data is valid
            int newData = 1;
            try {
                     newData = Integer.parseInt((String) pce.getNewValue());
            } catch (NumberFormatException e) {
                newData = -1;
            }
            if (newData <= 0) {
                // Signals the GUI to reject the entered value.
                throw new PropertyVetoException("Please enter a valid integer that is greater than zero.", pce);
            }
            // Save the state or data - bind with a database or
            // some other action.  Here we'll just update a "state" variable
            m_data = newData;
        }

        // Data entry completed - validate and switch back to main menu
        if (DataEntryPanel.PROPERTY_Done.equals(pce.getPropertyName())) {
            if (m_data <= 0) {
                // Request better data
                throw new PropertyVetoException("Please enter a valid integer that is greater than zero.", pce);
            }
            // Switch back to the Main menu
            cardLayout.show(contentPanel, MENUPANEL);
        }

        // Button pressed on the main menu
        if (MainMenuPanel.PROPERTY_MenuButton.equals(pce.getPropertyName())) {
            // This is a command to do something.  Using a vetoable change event
            // provides a nice mechanism to pass a message back to the GUI
            // if required.
            cardLayout.show(contentPanel, DATAPANEL);
        }
    }

    /**
     *  Show in the center of the screen.
     *  (pack, set location and set visibility)
     *  @param window Window to position
     */
    private void showCenterScreen(Window window) {
        positionScreen (window);
        window.setVisible(true);
        window.toFront();
    }   //  showCenterScreen

    /**
     *  Position window in center of the screen
     *  @param window Window to position
     */
    private void positionScreen (Window window)
    {
        window.pack();
        // take into account task bar and other adornments
        GraphicsConfiguration config = window.getGraphicsConfiguration();
        Rectangle bounds = config.getBounds();
        Dimension sSize = bounds.getSize();
        Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(config);
        sSize.width -= (insets.left + insets.right);
        sSize.height -= (insets.top + insets.bottom);

        Dimension wSize = window.getSize();
        //  fit on window
        if (wSize.height > sSize.height)
            wSize.height = sSize.height;
        if (wSize.width > sSize.width)
            wSize.width = sSize.width;
        window.setSize(wSize);
        //  Center
        int x = (sSize.width - wSize.width) / 2;
        int y = (sSize.height - wSize.height) / 2;
        //
        window.setLocation(bounds.x + x + insets.left, bounds.y + y + insets.top);
    }   //  positionScreen

/*****************************************************************************/

    /**
     * A simple demo GUI for the a main menu with a button.  This should be in its own file
     * but for stack overflow, its presented as a subclass.
     *
     */
    public class MainMenuPanel extends JPanel implements ActionListener, PropertyChangeListener {

        /**
         *  Constructor
         */
        public MainMenuPanel () {

            try {
                jbInit();
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        public final static String PROPERTY_MenuButton = "MenuButton";

        private GridBagLayout gridBagLayout = new GridBagLayout();

        private JLabel      lTitle = new JLabel();
        private JButton     bOption1 = new JButton();

        private void jbInit() {

            setLayout(gridBagLayout);

            // Label
            lTitle.setToolTipText("Click a Menu Button");
            lTitle.setText("Main Menu");

            // Menu Button
            bOption1.setToolTipText("Show the Data Entry Panel");
            bOption1.setText("Enter Data");
            bOption1.addActionListener(this);

            // Layout the fields
            this.add(lTitle,    new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
                ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 2, 5), 0, 0));

            this.add(bOption1,      new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
                ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0));

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == bOption1) {
                try {
                    fireVetoableChange(PROPERTY_MenuButton,0,1);
                } catch (PropertyVetoException e1) {
                    e1.printStackTrace();
                }
            }
        }

        // Property Change receives events from the controller
        // Doesn't do anything in this case but could be used to
        // change the menu based on state, show different entries
        // etc...
        @Override
        public void propertyChange(PropertyChangeEvent pce) {
            /* Example
            if (PROPERTY_APropertyName.equals(pce.getPropertyName())) {
                // do something relevant
            }
            */
        }
    }

/*****************************************************************************/

    /**
     * A simple demo GUI for the a data entry with a button.  This should be in its own file
     * but for stack overflow, its presented as a subclass.
     *
     */
    public class DataEntryPanel extends JPanel implements ActionListener, PropertyChangeListener {

        /**
         *  Constructor
         */
        public DataEntryPanel () {

            try {
                jbInit();
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        // Property definitions
        public final static String PROPERTY_Done = "DoneButton";
        public final static String PROPERTY_Data = "myData";

        private GridBagLayout gridBagLayout = new GridBagLayout();

        private JLabel              lData = new JLabel();
        private JFormattedTextField fData = new JFormattedTextField("0");
        private JButton             bDone = new JButton();

        private String lastGoodData = "0";
        private boolean m_settingValue;

        private void jbInit() {

            setLayout(gridBagLayout);

            // Label
            lData.setToolTipText("Enter a positive integer");
            lData.setText("Enter number:");

            // Field
            fData.setText(lastGoodData);
            fData.setEditable(true);
            fData.setHorizontalAlignment(SwingConstants.RIGHT);
            fData.addPropertyChangeListener("value", this);
            fData.setColumns(15);

            // Button
            bDone.setToolTipText("Save the data and return to the menu.");
            bDone.setText("Save/Done");
            bDone.addActionListener(this);

            // Layout the fields
            this.add(lData,    new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
                ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
            this.add(fData,    new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
                    ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));

            //grab extra space when window is maximized
            JPanel filler = new JPanel();
            filler.setOpaque(false);
            filler.setBorder(null);
            this.add(filler,        new GridBagConstraints(0, 1, 1, 1, 0.0, 1.0
                    ,GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));

            this.add(bDone,        new GridBagConstraints(1, 2, 2, 1, 0.0, 0.0
                ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(15, 5, 10, 5), 0, 0));

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // Ignore button events while a field is setting its value
            // This can happen if the field focus is lost to a button click
            if (e.getSource() == bDone && !m_settingValue) {
                try {
                    fireVetoableChange(PROPERTY_Done,0,1);
                } catch (PropertyVetoException pve) {
                    JOptionPane.showMessageDialog(null,
                              pve.getMessage(), "Error Massage",
                              JOptionPane.ERROR_MESSAGE);
                }
            }
        }

        // Property Change receives events from the controller or fields
        @Override
        public void propertyChange(PropertyChangeEvent pce) {

            m_settingValue = true;
            // The "value" property signals a change in a field value
            // Send the new value to the controller/model for validation
            if (fData.equals(pce.getSource()) && "value".equals(pce.getPropertyName())) {
                // Record the old value in case the change is vetoed. Don't use
                // the pce.getOldValue(), it isn't always accurate.
                String oldValue = lastGoodData;
                String newValue = (String) pce.getNewValue();

                try {
                    fireVetoableChange(PROPERTY_Data, oldValue, newValue);
                    lastGoodData = newValue;
                } catch (PropertyVetoException e) {
                    JOptionPane.showMessageDialog(null,
                              e.getMessage(), "Error Massage",
                              JOptionPane.ERROR_MESSAGE);
                    // Reset fData outside of the "value" event thread/loop
                    // Otherwise the value is not updated to the oldValue
                    EventQueue.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            fData.setText(lastGoodData);
                        }
                    });
                }
                m_settingValue = false;
            }
        }
    }
}


问:
Opendaylight: Message Deserialization failed. How to correlate to flow?
I have the following exception in my log:

```<code> Message deserialization failed
  java.lang.IllegalStateException: Deserializer for key: msgVersion: 4    objectClass: org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage msgType: 65535 experimenterID: 1330529792 was not found - please verify that all needed deserializers ale loaded correctly
</code>```

This is occurring because of some flow that my ODL java application previously wrote into the config data store (which was subsequently written to the switch by the southbound API) but I don't know which the offending flow is. I would like to know how to debug this. How can I correlate this exception to the corresponding flow?

Thanks,

Ranga

答:
This could be known bug https://jira.opendaylight.org/projects/OPNFLWPLUG/issues/OPNFLWPLUG-917 ?

PS, disclaimer: I know very openflowplugin [OFP] internals; just saw this by chance and thought this would be of interest to you.  You could contact https://lists.opendaylight.org/mailman/listinfo/openflowplugin-dev for more.

Body:
I have the following exception in my log:

 Message deserialization failed
  java.lang.IllegalStateException: Deserializer for key: msgVersion: 4    objectClass: org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage msgType: 65535 experimenterID: 1330529792 was not found - please verify that all needed deserializers ale loaded correctly

This is occurring because of some flow that my ODL java application previously wrote into the config data store (which was subsequently written to the switch by the southbound API) but I don't know which the offending flow is. I would like to know how to debug this. How can I correlate this exception to the corresponding flow?

Thanks,

Ranga


问:
Decode UDP Packet to Netflow
I've come across the Wireshark decode as feature where I can decode UDP packet as CFLOW to get my Netflow data.

Is it possible to code a script that decode the UDP Packet and get the Netflow data?

Currently I am trying it out using python3-scapy. Where I sniff the
  interface and retrieve only UDP packet. I am stuck now as I don't know
  what I should do next.

Note: My focus is on Netflow Version 9

Below is my code:

```<code>from scapy.all import *

## Create a Packet Counter
counter = 0
INTERFACE = "<interface_name>"

## Define our Custom Action function
def custom_action(pkts):
    for packet in pkts:
        if (packet.haslayer(UDP)):
             # do something , what should i do?

if __name__ == "__main__":
    ## Setup sniff, filtering for IP traffic
    sniff(iface=INTERFACE, prn = custom_action, store=0)
</code>```

答:
FYI, you can use layer in pkt rather than the "old" pkt.haslayer(layer). This will work with the development version of Scapy (which works with Python 3).

The prn callback accepts a packet, not a packet list or generator.

If you want to use NetflowHeader() to (try to) dissect any UDP packet, you can do:

```<code>def custom_action(pkt):
    if UDP in pkt:
        pkt[UDP].payload = NetflowHeader(raw(pkt[UDP].payload))

pkts = sniff(iface=INTERFACE, prn=custom_action)
</code>```

But the closest way to Wireshark's "decode as" functionality in Scapy would be to simply overwrite UDP's .payload_guess attribute:

```<code>UDP.payload_guess = [({}, NetflowHeader)]
pkts = sniff(iface=INTERFACE)
</code>```

Title: Decode UDP Packet to Netflow

Body:
I've come across the Wireshark decode as feature where I can decode UDP packet as CFLOW to get my Netflow data.

Is it possible to code a script that decode the UDP Packet and get the Netflow data?

Currently I am trying it out using python3-scapy. Where I sniff the
  interface and retrieve only UDP packet. I am stuck now as I don't know
  what I should do next.

Note: My focus is on Netflow Version 9

Below is my code:

from scapy.all import *

## Create a Packet Counter
counter = 0
INTERFACE = "<interface_name>"

## Define our Custom Action function
def custom_action(pkts):
    for packet in pkts:
        if (packet.haslayer(UDP)):
             # do something , what should i do?

if __name__ == "__main__":
    ## Setup sniff, filtering for IP traffic
    sniff(iface=INTERFACE, prn = custom_action, store=0)

Body:
FYI, you can use layer in pkt rather than the "old" pkt.haslayer(layer). This will work with the development version of Scapy (which works with Python 3).

The prn callback accepts a packet, not a packet list or generator.

If you want to use NetflowHeader() to (try to) dissect any UDP packet, you can do:

def custom_action(pkt):
    if UDP in pkt:
        pkt[UDP].payload = NetflowHeader(raw(pkt[UDP].payload))

pkts = sniff(iface=INTERFACE, prn=custom_action)

But the closest way to Wireshark's "decode as" functionality in Scapy would be to simply overwrite UDP's .payload_guess attribute:

UDP.payload_guess = [({}, NetflowHeader)]
pkts = sniff(iface=INTERFACE)


问:
SQL Where with Binary(n) column
I have a stored procedure:

```<code>ALTER PROCEDURE [dbo].[spUpdateOrInsertNotification]
    @ContentJsonHash BINARY(32)
AS
    DECLARE @NotificationId INT;

    SET @NotificationId = (SELECT @NotificationId
                           FROM dbo.tblNotifications n
                           WHERE n.ContentJsonHash = @ContentJsonHash);

    IF @NotificationId IS NOT NULL
    BEGIN
        -- Increment Count
    END
    ELSE
    BEGIN
         -- Insert new row.
    END
</code>```

It's supposed to check if the Hash already exists and if it does, increment the count for the row, otherwise insert the row. However, it never finds the Hash and the corresponding NotificationId. NotificationId is always null.

If I run it twice, passing it the same data (a C# array byte[32]). It never finds the same NotificationId and I end up with duplicate entries being put in.

e.g.

```<code>NotificationId | ContentJsonHash
9                0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
10               0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
</code>```

Can I not do comparisons on Binary(n) fields like this WHERE n.ContentJsonHash = @ContentJsonhash ?

The C# code:

```<code>using (var conn = new SqlConnection(Sql.ConnectionString))
{
     await conn.OpenAsync();

     using (var cmd = new SqlCommand(Sql.SqlUpdateOrInsertNotification, conn))
     {
          cmd.CommandType = CommandType.StoredProcedure;

          cmd.Parameters.AddWithValue("@Source", notificationMessage.Source);
          cmd.Parameters.AddWithValue("@Sender", notificationMessage.Sender);
          cmd.Parameters.AddWithValue("@NotificationType", notificationMessage.NotificationType);
          cmd.Parameters.AddWithValue("@ReceivedTimestamp", notificationMessage.Timestamp);
          cmd.Parameters.AddWithValue("@ContentJSon", notificationMessage.NotificationContent);
          cmd.Parameters.AddWithValue("@ContentJsonHash", notificationMessage.ContentHashBytes);

          await cmd.ExecuteNonQueryAsync();
    }
}
</code>```

I've also tried calling the stored procedure from SQL like this:

```<code>exec dbo.spUpdateOrInsertNotification 'foo', 'bar',  0,
                                      '2017-12-05 15:23:41.207', '{}',
                              0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
</code>```

Calling this twice returns 2 rows :(

I can do this, which works, hard coding the binary field I want to check

```<code>select *
from dbo.tblNotifications
where ContentJsonhash = 0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
</code>```

答:
Binary comparisons can be tricky. If you are using a true binary column, I believe length also comes into play. So even if those bytes are the same, and the lengths differ, the comparison would be false. An easy way is to convert these to strings:</p>

```<code>alter procedure [dbo].[spUpdateOrInsertNotification]
    @ContentJsonHash BINARY(32)
AS

DECLARE @NotificationId INT;
SET @NotificationId = (SELECT NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));

IF @NotificationId IS NOT NULL
BEGIN
   -- Increment Count
END
ELSE
BEGIN
   -- Insert new row.
END
</code>```

Title: SQL Where with Binary(n) column

Body:
I have a stored procedure:

ALTER PROCEDURE [dbo].[spUpdateOrInsertNotification]
    @ContentJsonHash BINARY(32)
AS
    DECLARE @NotificationId INT;

    SET @NotificationId = (SELECT @NotificationId
                           FROM dbo.tblNotifications n
                           WHERE n.ContentJsonHash = @ContentJsonHash);

    IF @NotificationId IS NOT NULL
    BEGIN
        -- Increment Count
    END
    ELSE
    BEGIN
         -- Insert new row.
    END

It's supposed to check if the Hash already exists and if it does, increment the count for the row, otherwise insert the row. However, it never finds the Hash and the corresponding NotificationId. NotificationId is always null.

If I run it twice, passing it the same data (a C# array byte[32]). It never finds the same NotificationId and I end up with duplicate entries being put in.

e.g.

NotificationId | ContentJsonHash
9                0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
10               0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A

Can I not do comparisons on Binary(n) fields like this WHERE n.ContentJsonHash = @ContentJsonhash ?

The C# code:

using (var conn = new SqlConnection(Sql.ConnectionString))
{
     await conn.OpenAsync();

     using (var cmd = new SqlCommand(Sql.SqlUpdateOrInsertNotification, conn))
     {
          cmd.CommandType = CommandType.StoredProcedure;

          cmd.Parameters.AddWithValue("@Source", notificationMessage.Source);
          cmd.Parameters.AddWithValue("@Sender", notificationMessage.Sender);
          cmd.Parameters.AddWithValue("@NotificationType", notificationMessage.NotificationType);
          cmd.Parameters.AddWithValue("@ReceivedTimestamp", notificationMessage.Timestamp);
          cmd.Parameters.AddWithValue("@ContentJSon", notificationMessage.NotificationContent);
          cmd.Parameters.AddWithValue("@ContentJsonHash", notificationMessage.ContentHashBytes);

          await cmd.ExecuteNonQueryAsync();
    }
}

I've also tried calling the stored procedure from SQL like this:

exec dbo.spUpdateOrInsertNotification 'foo', 'bar',  0,
                                      '2017-12-05 15:23:41.207', '{}',
                              0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A

Calling this twice returns 2 rows :(

I can do this, which works, hard coding the binary field I want to check

select *
from dbo.tblNotifications
where ContentJsonhash = 0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A

Body:
Binary comparisons can be tricky. If you are using a true binary column, I believe length also comes into play. So even if those bytes are the same, and the lengths differ, the comparison would be false. An easy way is to convert these to strings:

alter procedure [dbo].[spUpdateOrInsertNotification]
    @ContentJsonHash BINARY(32)
AS

DECLARE @NotificationId INT;
SET @NotificationId = (SELECT NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));

IF @NotificationId IS NOT NULL
BEGIN
   -- Increment Count
END
ELSE
BEGIN
   -- Insert new row.
END


问:
Sort values that come from different instances of the same class
I want to sort the order of the football clubs based on their points. I have created a class that get the values from the internet and process that values to calculate points based on the number of wins, loses and draws. Then I want to write the standings and their data onto a text file in that order. I created 20 different instances for 20 different clubs. However, I don't know what is the best way to sort the order.

```<code>import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CalculateStandings {
    private int matches;
    private int homeWin;
    private int homeDraw;
    private int homeLost;
    private int homeForGoal;
    private int homeAgainstGoal;
    private int awayWin;
    private int awayDraw;
    private int awayLost;
    private int awayForGoal;
    private int awayAgainstGoal;
    private int point;
    private int totalWin;
    private int totalLost;
    private int totalDraw;
    private int totalAgainstGoal;
    private int totalForGoal;

    void getResult(String team_Name) {
        try {
            URL url = new URL("https://raw.githubusercontent.com/openfootball/eng-england/master/2017-18/1-premierleague-i.txt");
        Scanner input = new Scanner(url.openStream());
        while (input.hasNext()) {
            String mydata = input.nextLine();
            if (mydata.contains(team_Name)) {
                Pattern pattern = Pattern.compile("[0-9]{1,2}-[0-9]{1,2}");
                Matcher matcher = pattern.matcher(mydata);
                String result;
                if (matcher.find()) {
                    matches += 1;
                    result = matcher.group();

                    if (mydata.startsWith("  " + team_Name)) {
                        homeForGoal += Integer.parseInt(Character.toString(result.charAt(0)));
                        homeAgainstGoal += Integer.parseInt(Character.toString(result.charAt(2)));
                    } else if (mydata.endsWith("  " + team_Name)) {
                        awayForGoal += Integer.parseInt(Character.toString(result.charAt(2)));
                        awayAgainstGoal += Integer.parseInt(Character.toString(result.charAt(0)));
                    }

                    if (Integer.parseInt(Character.toString(result.charAt(0))) > Integer.parseInt(Character.toString(result.charAt(2)))) {
                        if (mydata.startsWith("  " + team_Name)) {
                            point += 3;
                            homeWin += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            awayLost += 1;
                        }
                    } else if (Integer.parseInt(Character.toString(result.charAt(0))) < Integer.parseInt(Character.toString(result.charAt(2)))) {
                        if (mydata.startsWith("  " + team_Name)) {
                            homeLost += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            point += 3;
                            awayWin += 1;
                        }

                    } else {
                        if (mydata.startsWith("  " + team_Name)) {
                            point += 1;
                            homeDraw += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            point += 1;
                            awayDraw += 1;
                        }
                    }
                }
            }
        }
        totalWin = homeWin + awayWin;
        totalLost = homeLost + awayLost;
        totalDraw = homeDraw + awayDraw;
        totalAgainstGoal = homeAgainstGoal + awayAgainstGoal;
        totalForGoal = homeForGoal + awayForGoal;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
}
</code>```

And this is my main class:

```<code>public class Launcher {
public static void main(String[] args) {

    CalculateStandings Arsenal = new CalculateStandings();
    CalculateStandings Tottenham = new CalculateStandings();
    CalculateStandings WHam = new CalculateStandings();
    CalculateStandings CPalace = new CalculateStandings();
    CalculateStandings MU = new CalculateStandings();
    CalculateStandings MC = new CalculateStandings();
    CalculateStandings Everton = new CalculateStandings();
    CalculateStandings Liv = new CalculateStandings();
    CalculateStandings WBAlbion = new CalculateStandings();
    CalculateStandings NU = new CalculateStandings();
    CalculateStandings Stoke_City = new CalculateStandings();
    CalculateStandings Southampton = new CalculateStandings();
    CalculateStandings Leicester_City = new CalculateStandings();
    CalculateStandings Bournemouth = new CalculateStandings();
    CalculateStandings Watford = new CalculateStandings();
    CalculateStandings Brighton = new CalculateStandings();
    CalculateStandings Burnley = new CalculateStandings();
    CalculateStandings Huddersfield = new CalculateStandings();
    CalculateStandings Swansea = new CalculateStandings();

    Arsenal.getResult("Arsenal FC");
    Tottenham.getResult("Tottenham Hotspur");
    WHam.getResult("West Ham United");
    CPalace.getResult("Crystal Palace");
    MU.getResult("Manchester United");
    MC.getResult("Manchester City");
    Everton.getResult("Everton FC");
    Liv.getResult("Liverpool FC");
    WBAlbion.getResult("West Bromwich Albion");
    NU.getResult("Newcastle United");
    Stoke_City.getResult("Stoke City");
    Southampton.getResult("Southampton FC");
    Leicester_City.getResult("Leicester City");
    Bournemouth.getResult("AFC Bournemouth");
    Watford.getResult("Watford FC");
    Brighton.getResult("Brighton & Hove Albion");
    Burnley.getResult("Burnley FC");
    Huddersfield.getResult("Huddersfield Town");
    Swansea.getResult("Swansea City");

}

}
</code>```

I am thinking about storing the values into several arrays using Getter then sort them using sorting algorithm such as Bubble sort. However, as you can see, the number of instances and the number of fields inside each instances are numerous and write them into the arrays manually using Getter would take too much time. Therefore, I would like to ask you if there is a more optimized approach for this.

答:
Use List instead of array. You should also check on the Comparable interface and how to use it. So that later you can use sort method on the List.

https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

Body:
I want to sort the order of the football clubs based on their points. I have created a class that get the values from the internet and process that values to calculate points based on the number of wins, loses and draws. Then I want to write the standings and their data onto a text file in that order. I created 20 different instances for 20 different clubs. However, I don't know what is the best way to sort the order.

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CalculateStandings {
    private int matches;
    private int homeWin;
    private int homeDraw;
    private int homeLost;
    private int homeForGoal;
    private int homeAgainstGoal;
    private int awayWin;
    private int awayDraw;
    private int awayLost;
    private int awayForGoal;
    private int awayAgainstGoal;
    private int point;
    private int totalWin;
    private int totalLost;
    private int totalDraw;
    private int totalAgainstGoal;
    private int totalForGoal;

    void getResult(String team_Name) {
        try {
            URL url = new URL("https://raw.githubusercontent.com/openfootball/eng-england/master/2017-18/1-premierleague-i.txt");
        Scanner input = new Scanner(url.openStream());
        while (input.hasNext()) {
            String mydata = input.nextLine();
            if (mydata.contains(team_Name)) {
                Pattern pattern = Pattern.compile("[0-9]{1,2}-[0-9]{1,2}");
                Matcher matcher = pattern.matcher(mydata);
                String result;
                if (matcher.find()) {
                    matches += 1;
                    result = matcher.group();

                    if (mydata.startsWith("  " + team_Name)) {
                        homeForGoal += Integer.parseInt(Character.toString(result.charAt(0)));
                        homeAgainstGoal += Integer.parseInt(Character.toString(result.charAt(2)));
                    } else if (mydata.endsWith("  " + team_Name)) {
                        awayForGoal += Integer.parseInt(Character.toString(result.charAt(2)));
                        awayAgainstGoal += Integer.parseInt(Character.toString(result.charAt(0)));
                    }

                    if (Integer.parseInt(Character.toString(result.charAt(0))) > Integer.parseInt(Character.toString(result.charAt(2)))) {
                        if (mydata.startsWith("  " + team_Name)) {
                            point += 3;
                            homeWin += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            awayLost += 1;
                        }
                    } else if (Integer.parseInt(Character.toString(result.charAt(0))) < Integer.parseInt(Character.toString(result.charAt(2)))) {
                        if (mydata.startsWith("  " + team_Name)) {
                            homeLost += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            point += 3;
                            awayWin += 1;
                        }

                    } else {
                        if (mydata.startsWith("  " + team_Name)) {
                            point += 1;
                            homeDraw += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            point += 1;
                            awayDraw += 1;
                        }
                    }
                }
            }
        }
        totalWin = homeWin + awayWin;
        totalLost = homeLost + awayLost;
        totalDraw = homeDraw + awayDraw;
        totalAgainstGoal = homeAgainstGoal + awayAgainstGoal;
        totalForGoal = homeForGoal + awayForGoal;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
}

And this is my main class:

public class Launcher {
public static void main(String[] args) {

    CalculateStandings Arsenal = new CalculateStandings();
    CalculateStandings Tottenham = new CalculateStandings();
    CalculateStandings WHam = new CalculateStandings();
    CalculateStandings CPalace = new CalculateStandings();
    CalculateStandings MU = new CalculateStandings();
    CalculateStandings MC = new CalculateStandings();
    CalculateStandings Everton = new CalculateStandings();
    CalculateStandings Liv = new CalculateStandings();
    CalculateStandings WBAlbion = new CalculateStandings();
    CalculateStandings NU = new CalculateStandings();
    CalculateStandings Stoke_City = new CalculateStandings();
    CalculateStandings Southampton = new CalculateStandings();
    CalculateStandings Leicester_City = new CalculateStandings();
    CalculateStandings Bournemouth = new CalculateStandings();
    CalculateStandings Watford = new CalculateStandings();
    CalculateStandings Brighton = new CalculateStandings();
    CalculateStandings Burnley = new CalculateStandings();
    CalculateStandings Huddersfield = new CalculateStandings();
    CalculateStandings Swansea = new CalculateStandings();

    Arsenal.getResult("Arsenal FC");
    Tottenham.getResult("Tottenham Hotspur");
    WHam.getResult("West Ham United");
    CPalace.getResult("Crystal Palace");
    MU.getResult("Manchester United");
    MC.getResult("Manchester City");
    Everton.getResult("Everton FC");
    Liv.getResult("Liverpool FC");
    WBAlbion.getResult("West Bromwich Albion");
    NU.getResult("Newcastle United");
    Stoke_City.getResult("Stoke City");
    Southampton.getResult("Southampton FC");
    Leicester_City.getResult("Leicester City");
    Bournemouth.getResult("AFC Bournemouth");
    Watford.getResult("Watford FC");
    Brighton.getResult("Brighton & Hove Albion");
    Burnley.getResult("Burnley FC");
    Huddersfield.getResult("Huddersfield Town");
    Swansea.getResult("Swansea City");

}

}

I am thinking about storing the values into several arrays using Getter then sort them using sorting algorithm such as Bubble sort. However, as you can see, the number of instances and the number of fields inside each instances are numerous and write them into the arrays manually using Getter would take too much time. Therefore, I would like to ask you if there is a more optimized approach for this.


问:
How to add a sort query to my StructuredQueryBuilder before talking to Marklogic
I am trying to add a sort/ordering query.

At my java:

```<code>StructuredQueryBuilder qb = new StructuredQueryBuilder();
QueryDefinition queryDef = qb.and(qb.value(qb.jsonProperty("status"), "Active"));
SearchHandle resultsHandle = new SearchHandle();
queryManager.setPageLength(PAGE_SIZE_TEN);
int start = PAGE_SIZE_TEN * (pageNumber - 1) + 1;
queryManager.search(queryDef, resultsHandle, start);
</code>```

The above will return the resultsHandle with 10 json files found for each page specified for the variable "start", with status "Active".

My question is how do I include a sorting query like maybe something along the line of the following:

```<code>QueryDefinition queryDef = qb.and(qb.value(qb.jsonProperty("status"), "Active"),
                                  qb.sort?(qb.jsonProperty("dateCreated"));
</code>```

I want it to get me the 1st 10 json files in order of latest date. It is too late to do a Comparator after getting the result, as the result returns a random 10 json files not in any particular order.

A few samples of the json files will look as such:
1.json

```<code>[
 {
  "id":"1",
  "dateCreated":"2017-10-01 12:00:00",
  "status":"Active"
  "body":"This is a test"
 }
]
</code>```

2.json

```<code>[
 {
  "id":"2",
  "dateCreated":"2017-10-02 12:00:00",
  "status":"Active"
  "body":"This is a test 2"
 }
]
</code>```

I realized there's a enum StructuredQueryBuilder.Ordering, how do I use it?

答:
StructuredQueryBuilder.Ordering is specifically for use with near-query and is unrelated to what you want to do. You need to use query options to define a sort order for your search results. See the sort-order query option:

http://docs.marklogic.com/guide/search-dev/appendixa#id_44212

Options can be pre-defined and installed on MarkLogic and then referenced in your search, or you can define them at runtime and combine them with your structured query in a combined query.

Predefined: http://docs.marklogic.com/guide/java/query-options#chapter

Dynamic: http://docs.marklogic.com/guide/java/searches#id_76144

Body:
I am trying to add a sort/ordering query.

At my java:

StructuredQueryBuilder qb = new StructuredQueryBuilder();
QueryDefinition queryDef = qb.and(qb.value(qb.jsonProperty("status"), "Active"));
SearchHandle resultsHandle = new SearchHandle();
queryManager.setPageLength(PAGE_SIZE_TEN);
int start = PAGE_SIZE_TEN * (pageNumber - 1) + 1;
queryManager.search(queryDef, resultsHandle, start);

The above will return the resultsHandle with 10 json files found for each page specified for the variable "start", with status "Active".

My question is how do I include a sorting query like maybe something along the line of the following:

QueryDefinition queryDef = qb.and(qb.value(qb.jsonProperty("status"), "Active"),
                                  qb.sort?(qb.jsonProperty("dateCreated"));

I want it to get me the 1st 10 json files in order of latest date. It is too late to do a Comparator after getting the result, as the result returns a random 10 json files not in any particular order.

A few samples of the json files will look as such:
1.json

[
 {
  "id":"1",
  "dateCreated":"2017-10-01 12:00:00",
  "status":"Active"
  "body":"This is a test"
 }
]

2.json

[
 {
  "id":"2",
  "dateCreated":"2017-10-02 12:00:00",
  "status":"Active"
  "body":"This is a test 2"
 }
]

I realized there's a enum StructuredQueryBuilder.Ordering, how do I use it?


问:
Installing Numpy and Scipy - Can't find system python 2.6
I"m trying to install numpy and scipy for a data analysis class I have this semester. I'm trying to install it from the package on sourceforge.net, but as I follow the wizard I can't select my HD. There is a message saying numpy.1.5.1 requires System Python 2.6. I know it is there as when I type $ python version 2.6.1 comes up.

I've done a bit of snooping under the hood and it looks like python 2.6 is under usr/bin where as python3 is in usr/local/bin.  I'm a bit new with the terminal so I'm not sure if I can throw the files in the local/bin, or if this is even the issue.

Thanks in advance

Operating System: OS X 10.6.6

答: The official Numpy 1.5.1 installer for Python 2.6 for OS X appear to require the python.org Python 2.6, not the Apple-supplied Python 2.6.</p>


问:
How to find any element in a HashMap where a given condition about that element is true

Given an object, MyObj which for our purposes holds String message among other fields.

Given a HashMap, Map <MultiKey<String>,MyObj> map.

I want to loop through the HashMap finding any element where the MyObj's message is searchValue. I'm essentially trying to use stream().anyMatch() on a Map, I simply want to know if searchValue exists even once anywhere - i.e. short circuiting is preferable.

Foreach loop:

```<code>map.forEach((k,v) -> {
    if (v.message.equalsIgnoreCase(searchValue)) {
        return true;
    }
}
</code>```

The issue with this is that it doesn't terminate early, neither break or return can be used in this lambda to terminate the loop early.

I see the stream anyMatch() function:

```<code> map.entrySet().stream().anymatch(....
</code>```

but I can't figure out the proper syntax - if that will work in this case at all (can it still be used if I'm not comparing the map's elements, rather I'm comparing each element's fields).

答:
One way to solve that is by using findFirst method.

In your case, for example, you can write something like this:

```<code> map.values().stream()
            .filter(e -> e.message.equalsIgnoreCase(searchValue))
            .findFirst()
            .get();
</code>```

Body:
Given an object, MyObj which for our purposes holds String message among other fields.

Given a HashMap, Map <MultiKey<String>,MyObj> map.

I want to loop through the HashMap finding any element where the MyObj's message is searchValue. I'm essentially trying to use stream().anyMatch() on a Map, I simply want to know if searchValue exists even once anywhere - i.e. short circuiting is preferable.

Foreach loop:

map.forEach((k,v) -> {
    if (v.message.equalsIgnoreCase(searchValue)) {
        return true;
    }
}

The issue with this is that it doesn't terminate early, neither break or return can be used in this lambda to terminate the loop early.

I see the stream anyMatch() function:

 map.entrySet().stream().anymatch(....

but I can't figure out the proper syntax - if that will work in this case at all (can it still be used if I'm not comparing the map's elements, rather I'm comparing each element's fields).

Body:
One way to solve that is by using findFirst method.

In your case, for example, you can write something like this:

 map.values().stream()
            .filter(e -> e.message.equalsIgnoreCase(searchValue))
            .findFirst()
            .get();


问:
Can grep read from a file and stdin at the same time?
file1:

```<code>abcds
asdt5ds
</code>```

file2:

```<code>1
2
3
4
5
</code>```

Output:

```<code>asdt5ds
5
</code>```

Is it possible to get such output using a variation of cat file1 | grep 5 file2?

答:
You can use the special file - (for "standard input"):

```<code>cat file1 | grep 5 - file2
</code>```

If you want to suppress the filenames, i.e., if you don't want this output

```<code>(standard input):asdt5ds
file2:5
</code>```

you can do that using the -h option.

Notice that both of these (using - as special file name and -h to suppress file names) are not required by POSIX, but at least GNU grep supports them.

Body:
file1:

abcds
asdt5ds

file2:

1
2
3
4
5

Output:

asdt5ds
5

Is it possible to get such output using a variation of cat file1 | grep 5 file2?

Body:
You can use the special file - (for "standard input"):

cat file1 | grep 5 - file2

If you want to suppress the filenames, i.e., if you don't want this output

(standard input):asdt5ds
file2:5

you can do that using the -h option.

Notice that both of these (using - as special file name and -h to suppress file names) are not required by POSIX, but at least GNU grep supports them.


问:
When attempting to use all available RAM, only 2 GB are used before the program terminates
When I execute the following code, the RAM usage increases very rapidly in Task Manager. However, at about just under 2 GB, it severely slows down, and then I receive the error "This application has requested the Runtime to terminate it in an unusual way."

```<code>while(true){
   int *pointer66 = new int;
}
</code>```

What is happening at the 2 GB mark? Is Windows throttling it?

I first assumed it might be the antivirus, so I disabled that, but that didn't do anything.

答: Per your last comment, the program likely fails due to an unhandled C++ exception. Windows doesn't exactly understand what failed, so it just reports an unusual exit. </p>

Body:
When I execute the following code, the RAM usage increases very rapidly in Task Manager. However, at about just under 2 GB, it severely slows down, and then I receive the error "This application has requested the Runtime to terminate it in an unusual way."

while(true){
   int *pointer66 = new int;
}

What is happening at the 2 GB mark? Is Windows throttling it?

I first assumed it might be the antivirus, so I disabled that, but that didn't do anything.


问:
Database sequences: Why incrementing by other than 1?
I am wondering, why you should use an increment by something other that "1".

I know, that sequences can have gaps, for example because of caching, but this is not what I am asking now. I would like to know, why it should be better to use

```<code>create sequence SEQ start with 1 increment by 20
</code>```

instead of

```<code>create sequence SEQ start with 1 increment by 1
</code>```

Oracle, I think, for example uses an increment of 20, JPA (Java Persistence API) defines sequences with an increment of 50 by default.

But what is the advantage?

And what value should I use?

Thank you for answering! Kind regards!

答:
The purpose I know is that if you have a dataset stored on 20 database servers. If they each incremented by 1, they'd generate the same values, and it would be hard to merge the data if you ever need to do that.

If each of the 20 servers increment by 20, and each one starts at a different offset, then they'll all allocate distinct id's. So if you need to merge them for reports, or as you re-build your set of servers, you won't have conflicts.

Body:
I am wondering, why you should use an increment by something other that "1".

I know, that sequences can have gaps, for example because of caching, but this is not what I am asking now. I would like to know, why it should be better to use

create sequence SEQ start with 1 increment by 20

instead of

create sequence SEQ start with 1 increment by 1

Oracle, I think, for example uses an increment of 20, JPA (Java Persistence API) defines sequences with an increment of 50 by default.

But what is the advantage?

And what value should I use?

Thank you for answering! Kind regards!


问:
Error installing "node-red-contrib-freeboard"
I have installed node-red successfully.Its working,
But now i want to install "node-red-contrib-freeboard".

But when i hit the "npm install node-red-contrib-freeboard" command in my node red root directory I get this error:

```<code>node-red-contrib-freeboard@0.0.7 postinstall /root/.node-red/node_modules/node-red-contrib-freeboard
> node rewritefiles.js

{ Error: ENOENT: no such file or directory, open 'node_modules/freeboard/index.html'
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'node_modules/freeboard/index.html' }
{ Error: ENOENT: no such file or directory, open 'node_modules/freeboard/js/freeboard.js'
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'node_modules/freeboard/js/freeboard.js' }
events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: ENOENT: no such file or directory, open 'node_modules/freeboard/plugins/thirdparty/jquery.keyframes.min.js'
npm WARN node-red-project@0.0.1 No repository field.
npm WARN node-red-project@0.0.1 No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-red-contrib-freeboard@0.0.7 postinstall: `node rewritefiles.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-red-contrib-freeboard@0.0.7 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-12-05T16_35_42_862Z-debug.log
</code>```

Please help me to make it run.How do I resolve this issue??

答:
looks like in issue with version 0.0.7

https://github.com/urbiworx/node-red-contrib-freeboard/issues/28

try installing the previous version and see if the issue still occurs. check back on the github issue to see when it is corrected.

Body:
I have installed node-red successfully.Its working,
But now i want to install "node-red-contrib-freeboard".

But when i hit the "npm install node-red-contrib-freeboard" command in my node red root directory I get this error:

node-red-contrib-freeboard@0.0.7 postinstall /root/.node-red/node_modules/node-red-contrib-freeboard
> node rewritefiles.js

{ Error: ENOENT: no such file or directory, open 'node_modules/freeboard/index.html'
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'node_modules/freeboard/index.html' }
{ Error: ENOENT: no such file or directory, open 'node_modules/freeboard/js/freeboard.js'
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'node_modules/freeboard/js/freeboard.js' }
events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: ENOENT: no such file or directory, open 'node_modules/freeboard/plugins/thirdparty/jquery.keyframes.min.js'
npm WARN node-red-project@0.0.1 No repository field.
npm WARN node-red-project@0.0.1 No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-red-contrib-freeboard@0.0.7 postinstall: `node rewritefiles.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-red-contrib-freeboard@0.0.7 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-12-05T16_35_42_862Z-debug.log

Please help me to make it run.How do I resolve this issue??


问:
python version 3.6.3 Functions and lists
I am trying to run the following:

```<code>def count_small(numbers):
total = 0
for n in numbers:
    if n < 10:
        total = total + 1
    return total

lotto = [4, 8, 15, 16, 23, 42]
small = count_small(lotto)
print(small)
</code>```

Here I have defined a function 'count_small(numbers)'
it starts with a total of 0,
then checks each item in the list, to check that it is less than 10, if the item is less then 10, then 1 will be added to the total. I am running the function on the list 'lotto', as you can see 'lotto' has two numbers less than 10 '4' and '8' hence it should return 2, however, when I run the code it returns 1 instead.

答:
Your return statement is inside the for-loop, so that the function is left after the first number.

```<code>def count_small(numbers):
    total = 0
    for n in numbers:
        if n < 10:
            total += 1
    return total
</code>```

When you use a generator expression, you can write this in one line:

```<code>def count_small(numbers):
    return sum(n<10 for n in numbers)
</code>```

Body:
I am trying to run the following:

def count_small(numbers):
total = 0
for n in numbers:
    if n < 10:
        total = total + 1
    return total

lotto = [4, 8, 15, 16, 23, 42]
small = count_small(lotto)
print(small)

Here I have defined a function 'count_small(numbers)'
it starts with a total of 0,
then checks each item in the list, to check that it is less than 10, if the item is less then 10, then 1 will be added to the total. I am running the function on the list 'lotto', as you can see 'lotto' has two numbers less than 10 '4' and '8' hence it should return 2, however, when I run the code it returns 1 instead.

Body:
Your return statement is inside the for-loop, so that the function is left after the first number.

def count_small(numbers):
    total = 0
    for n in numbers:
        if n < 10:
            total += 1
    return total

When you use a generator expression, you can write this in one line:

def count_small(numbers):
    return sum(n<10 for n in numbers)