问:
URL decoding: UnsupportedEncodingException in Java
What I understand from the documentation is that UnsupportedEncodingException can only be thrown if I specify a wrong encoding as the second parameter to URLDecoder.decode(String, String) method. Is it so? I need to know cases where this exception can be thrown.

Basically, I have this code segment in one of my functions:

```<code>if (keyVal.length == 2) {
    try {
        value = URLDecoder.decode(
            keyVal[1],
            "UTF-8");
    } catch (UnsupportedEncodingException e) {
          // Will it ever be thrown?
    }
}
</code>```

Since I am explicitly mentioning "UTF-8", is there any way this exception can be thrown? Do I need to do anything in the catch block? Or, if my understanding is completely wrong, please let me know.

答:
It cannot happen, unless there is something fundamentally broken in your JVM.  But I think you should write this as:

```<code>try {
    value = URLDecoder.decode(keyVal[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
    throw new AssertionError("UTF-8 is unknown");
    // or 'throw new AssertionError("Impossible things are happening today. " +
    //                              "Consider buying a lottery ticket!!");'
}
</code>```

The cost of doing this is a few bytes of code that will "never" be executed, and one String literal that will never be used.  That a small price for the protecting against the possibility that you may have misread / misunderstood the javadocs (you haven't in this case ...) or that the specs might change (they won't in this case ...)

Body:
What I understand from the documentation is that UnsupportedEncodingException can only be thrown if I specify a wrong encoding as the second parameter to URLDecoder.decode(String, String) method. Is it so? I need to know cases where this exception can be thrown.

Basically, I have this code segment in one of my functions:

if (keyVal.length == 2) {
    try {
        value = URLDecoder.decode(
            keyVal[1],
            "UTF-8");
    } catch (UnsupportedEncodingException e) {
          // Will it ever be thrown?
    }
}

Since I am explicitly mentioning "UTF-8", is there any way this exception can be thrown? Do I need to do anything in the catch block? Or, if my understanding is completely wrong, please let me know.

Body:
It cannot happen, unless there is something fundamentally broken in your JVM.  But I think you should write this as:

try {
    value = URLDecoder.decode(keyVal[1], "UTF-8");
} catch (UnsupportedEncodingException e) {
    throw new AssertionError("UTF-8 is unknown");
    // or 'throw new AssertionError("Impossible things are happening today. " +
    //                              "Consider buying a lottery ticket!!");'
}

The cost of doing this is a few bytes of code that will "never" be executed, and one String literal that will never be used.  That a small price for the protecting against the possibility that you may have misread / misunderstood the javadocs (you haven't in this case ...) or that the specs might change (they won't in this case ...)


来源: stackexchange

问:
how we can split a data input where some of them are separated by one space and some with 2 space?
I have a data input as below:

```<code>[-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914]
[ 228 -114 -114  914  228 -114 -114  228  228 -114 -114  228  228 -114 -114]
</code>```

as you can see there is 1 space before  negative numbers and 2 spaces before positive.

I read file as this :

```<code>def switch(letter):
    switcher = {
        "[": "",
        "]": "",
        "\n": "@",
    }
    return switcher.get(letter, letter)

converted_data = ''
with open("/Users/naghmeh/Documents/python/core1", "r") as file:
    data = file.read()

for letter in data:
    letter = switch(letter)
    converted_data = converted_data+letter

converted_data = converted_data.split('@')
split_converted_data = []
for i in converted_data:
    i = i.split(" ")
    split_converted_data.append(i)
</code>```

which i = i.split(" ") separate by 1 space. so code can not be run correctly. how I can fix it?

答:
You can do:

```<code>for i in converted_data:
    i = i.replace('  ', ' ').split(' ')
    split_converted_data.append(i)
</code>```

To replace every pair of space by only one

ContentLicense: CC BY-SA 4.0

Body:
I have a data input as below:

[-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914]
[ 228 -114 -114  914  228 -114 -114  228  228 -114 -114  228  228 -114 -114]

as you can see there is 1 space before  negative numbers and 2 spaces before positive.

I read file as this :

def switch(letter):
    switcher = {
        "[": "",
        "]": "",
        "\n": "@",
    }
    return switcher.get(letter, letter)

converted_data = ''
with open("/Users/naghmeh/Documents/python/core1", "r") as file:
    data = file.read()

for letter in data:
    letter = switch(letter)
    converted_data = converted_data+letter

converted_data = converted_data.split('@')
split_converted_data = []
for i in converted_data:
    i = i.split(" ")
    split_converted_data.append(i)

which i = i.split(" ") separate by 1 space. so code can not be run correctly. how I can fix it?

Body:
You can do:

for i in converted_data:
    i = i.replace('  ', ' ').split(' ')
    split_converted_data.append(i)

To replace every pair of space by only one


问:
why do items disappear when i redock the window?
i tried printing out to a listbox the nlog exceptions using NLog Viewer  in avalon dock window

If i try to dock out the window the listbox is cleared out and its the same for docking the window with the listbox back.

How could i fix that?

xaml code

```<code> <Grid>
        <StackPanel Margin="0,10">
            <Grid Visibility="{Binding outputVisibility, UpdateSourceTrigger=PropertyChanged}">
                <nlog:NlogViewer x:Name="logCtrl"  MinHeight="300" MinWidth="1000"/>
            </Grid>

            <Button Command="{Binding ConvertTextCommand}" Margin="5" Height="35">PrintException</Button>
            <Button Command="{Binding HideTextBoxCommand}" Margin="5">Hide</Button>
        </StackPanel>
    </Grid>
</code>```

nlog config file

```<code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <extensions>
    <add assembly="NlogViewer" />
  </extensions>
  <targets>
    <target xsi:type="NlogViewer" name="ctrl" />
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="ctrl" />
  </rules>
</nlog>
</code>```

And I m using this to simulate exceptions.

```<code>try
            {
                counter++;
                if (counter % 2 == 0)
                    throw new OutOfMemoryException();
                else throw new ArgumentOutOfRangeException();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.StackTrace + " " + ex.Message);
            }
</code>```

UPDATE

I also noticed that even a simple text box with text will get cleared out after dock out or dock in

答:
I found that the issue was xceed avalon dock community version.

There is an issue about dockable pane reloading in xceed github project and they added a function to retain the info in the pane after docking in the premium version.

I solved this issue using Avalon Dock.

From my understanding this is a branch of the xceed project but with much more development. I just downloaded this with nuget package manager and uninstalled xceed avalon dock. Now the items are saved after dock in dock out

Body:
i tried printing out to a listbox the nlog exceptions using NLog Viewer  in avalon dock window

If i try to dock out the window the listbox is cleared out and its the same for docking the window with the listbox back.

How could i fix that?

xaml code

 <Grid>
        <StackPanel Margin="0,10">
            <Grid Visibility="{Binding outputVisibility, UpdateSourceTrigger=PropertyChanged}">
                <nlog:NlogViewer x:Name="logCtrl"  MinHeight="300" MinWidth="1000"/>
            </Grid>

            <Button Command="{Binding ConvertTextCommand}" Margin="5" Height="35">PrintException</Button>
            <Button Command="{Binding HideTextBoxCommand}" Margin="5">Hide</Button>
        </StackPanel>
    </Grid>

nlog config file

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <extensions>
    <add assembly="NlogViewer" />
  </extensions>
  <targets>
    <target xsi:type="NlogViewer" name="ctrl" />
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="ctrl" />
  </rules>
</nlog>

And I m using this to simulate exceptions.

try
            {
                counter++;
                if (counter % 2 == 0)
                    throw new OutOfMemoryException();
                else throw new ArgumentOutOfRangeException();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.StackTrace + " " + ex.Message);
            }

UPDATE

I also noticed that even a simple text box with text will get cleared out after dock out or dock in


问:
How to segregate higher numbers from lower numbers
```<code>import random
num = input('enter a number:')
n1=random.randrange(0,50)
n2=random.randrange(0,50)
n3=random.randrange(0,50)
n4=random.randrange(0,50)
n5=random.randrange(0,50)
</code>```

What i want to do is to compare those random numbers to my input number if the random number is higher it will be displayed all higher numbers than the user input also, it will display the smaller numbers compare to the user input at the same time
For example i entered
30
And the random numbers are 5, 45, 18, 22, 50
Output:
Higher number than 30 are: 45, 50
Lower number than 30 are: 5, 18, 22

I tried using if else but it wont display anything if the series of numbers are mixed like the example.

答:
```<code>import random
num = input('enter a number:')
random_numbers = []

# Generate all the numbers and store in a list
for i in range (0,5):
    random_numbers.append(random.randrange(0,50))

# Get lower values
lower = [number for number in random_numbers if number<num]
# Get higher ones
higher = [number for number in random_numbers if number>num]

print("Higher number than {num} are: " + str(higher))
print("Lower number than {num} are: " + str(lower))
</code>```

Body:
import random
num = input('enter a number:')
n1=random.randrange(0,50)
n2=random.randrange(0,50)
n3=random.randrange(0,50)
n4=random.randrange(0,50)
n5=random.randrange(0,50)

What i want to do is to compare those random numbers to my input number if the random number is higher it will be displayed all higher numbers than the user input also, it will display the smaller numbers compare to the user input at the same time
For example i entered
30
And the random numbers are 5, 45, 18, 22, 50
Output:
Higher number than 30 are: 45, 50
Lower number than 30 are: 5, 18, 22

I tried using if else but it wont display anything if the series of numbers are mixed like the example.


问:
Kubelet config yaml is missing when restart work node docker service
When I restart the docker service in work node, the logs of kubelet in master node report a no such file error.</p>

```<code># in work node
# systemctl restart docker service

# in master node
# journalctl -u kubelet
# failed to load Kubelet config file /var/lib/kubelet/config.yaml, error failed to read kubelet config file "/var/lib/kubelet/config.yaml", error: open /var/lib/kubelet/config.yaml: no such file or directory
</code>```

答:
Arghya is right but I would like to add some info you should be aware of:

You can execute kubeadm init phase kubelet-start to only invoke a particular step that will write the kubelet configuration file and environment file and then start the kubelet.

After performing a restart there is a chance that swap would re-enable. Make sure to run swapoff -a in order to turn it off.

If you encounter any token validation problems than simply run kubeadm token create --print-join-command and than do the join process with the provided info. Remember that tokens expire after 24 hours by default.

If you wish to know more about kubeadm init phase you can find it here and here.

Please let me know if that helped.

Body:
When I restart the docker service in work node, the logs of kubelet in master node report a no such file error.

# in work node
# systemctl restart docker service

# in master node
# journalctl -u kubelet
# failed to load Kubelet config file /var/lib/kubelet/config.yaml, error failed to read kubelet config file "/var/lib/kubelet/config.yaml", error: open /var/lib/kubelet/config.yaml: no such file or directory


问:
Openrefine: copy data from text facet into excel in readable way?
I am new to OpenRefine, I created a text facet for some data as shown here:

,

I would like to copy that info into excel in two columns one with the name of the data and another with the number, butI get everything in the same column as shown here:

.

Any smart idea to not fix it manually?

答: If you click the button in the top left of the facet that says "10 choices" it will give you the facet choices as tab separated values, which you can copy directly into a spreadsheet, and should format as two columns.</p>


Title: how we can split a data input where some of them are separated by one space and some with 2 space?

Body:
Use split() with no arguments

a = '-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914'
a = a.split()
print(a)
# ['-114', '-114', '228', '-114', '228', '228', '-114', '-114', '228', '228', '-114', '228', '-114', '-114', '914']


问:
How to add a Spring Boot support to an external library?
I have a library I'm developing, and let's say it offers some service FooService.

Now, in order to instantiate it you need to pass some arguments to the constructor.

Typically (if FooService is in the same project), you are supposed to write FooServiceConfig class annotated with @Configuration and instantiate using @Valueed properties.

How can it be done when you use FooService from an external library?

What I'd like to achieve is to be able to instantiate the FooService using @Autowired (and putting the correct config in application.properties)

答:
If your library is supposed to work within Spring's projects you can create your own auto-configuration.

Once you have everything configured it will work in the same way as any other spring-boot-starter.


问:
Equal Height constraints between different UIStackView's subviews
I have a constraint scenario which works perfectly when built through interface builder but I cannot make it through code. The screen layout is the following:

A Horizontal UIStackView with multiple vertical UIStackView inline. Each one of these vertical UIStackView's has multiple UIView's inside it. What I'm trying to achieve is the following: inline UIView with equal height

When creating such constraints through interface builder, it works perfectly:

But when creating this constraints through code I face the following error:

'Unable to activate constraint with anchors <NSLayoutDimension:0x600002b9a6c0 "UIView:0x7f9e6f075c30.height"> and <NSLayoutDimension:0x600002b9a700 "UIView:0x7f9e6c423d50.height"> because they have no common ancestor.  Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'

I've tried creating these constraints using the following ways:

1.

```<code>let heightConstraint = NSLayoutConstraint(item: view1,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: view2,
                                          attribute: .height,
                                          multiplier: 1,
                                          constant: 0)
NSLayoutConstraint.activate([heightConstraint])
</code>```

2.

```<code>let heightConstraint = NSLayoutConstraint(item: view1,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: view2,
                                          attribute: .height,
                                          multiplier: 1,
                                          constant: 0)
horizontalStackView.addConstraint(heightConstraint)
</code>```

where horizontalStackView is the horizontal stackview that holds all vertical stackviews.

I cannot figure out where this constraints were added to work through interface builder to create them through code.

答:
Here is how you can get the above UI using code,

1. Create the UIView's with relevant backgroundColors,

```<code>    let v1 = UIView()
    v1.backgroundColor = #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1)
    v1.translatesAutoresizingMaskIntoConstraints = false

    let v2 = UIView()
    v2.backgroundColor = #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
    v2.translatesAutoresizingMaskIntoConstraints = false

    let v3 = UIView()
    v3.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
    v3.translatesAutoresizingMaskIntoConstraints = false

    let v4 = UIView()
    v4.backgroundColor = #colorLiteral(red: 0.5058823824, green: 0.3372549117, blue: 0.06666667014, alpha: 1)
    v4.translatesAutoresizingMaskIntoConstraints = false

    let v5 = UIView()
    v5.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
    v5.translatesAutoresizingMaskIntoConstraints = false

    let v6 = UIView()
    v6.backgroundColor = #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1)
    v6.translatesAutoresizingMaskIntoConstraints = false

    let v7 = UIView()
    v7.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
    v7.translatesAutoresizingMaskIntoConstraints = false

    let v8 = UIView()
    v8.backgroundColor = #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)
    v8.translatesAutoresizingMaskIntoConstraints = false

    let v9 = UIView()
    v9.backgroundColor = #colorLiteral(red: 0.06274510175, green: 0, blue: 0.1921568662, alpha: 1)
    v9.translatesAutoresizingMaskIntoConstraints = false
</code>```

2. Create the horizontalStackViews with the above created UIViews. Don't forget to set the distribution as fillEqually

```<code>    let hStack1 = UIStackView(arrangedSubviews: [v1, v2, v3])
    hStack1.axis = .horizontal
    hStack1.distribution = .fillEqually
    hStack1.translatesAutoresizingMaskIntoConstraints = false

    let hStack2 = UIStackView(arrangedSubviews: [v4, v5, v6])
    hStack2.axis = .horizontal
    hStack2.distribution = .fillEqually
    hStack2.translatesAutoresizingMaskIntoConstraints = false

    let hStack3 = UIStackView(arrangedSubviews: [v7, v8, v9])
    hStack3.axis = .horizontal
    hStack3.distribution = .fillEqually
    hStack3.translatesAutoresizingMaskIntoConstraints = false
</code>```

3. Create the verticalStackView using the above created horizontalStackViews and set its distribution as fillEqually as well

```<code>    let vStack = UIStackView(arrangedSubviews: [hStack1, hStack2, hStack3])
    vStack.axis = .vertical
    vStack.distribution = .fillEqually
    vStack.translatesAutoresizingMaskIntoConstraints = false
</code>```

4. Add the vStack the controller's view,

```<code>    self.view.addSubview(vStack)
</code>```

5. Add the below constraints to the vStack,

```<code>    vStack.heightAnchor.constraint(equalToConstant: 200).isActive = true
    vStack.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    vStack.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    vStack.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
</code>```

Screenshot:

Body:
I have a constraint scenario which works perfectly when built through interface builder but I cannot make it through code. The screen layout is the following:

A Horizontal UIStackView with multiple vertical UIStackView inline. Each one of these vertical UIStackView's has multiple UIView's inside it. What I'm trying to achieve is the following: inline UIView with equal height

When creating such constraints through interface builder, it works perfectly:

But when creating this constraints through code I face the following error:

'Unable to activate constraint with anchors <NSLayoutDimension:0x600002b9a6c0 "UIView:0x7f9e6f075c30.height"> and <NSLayoutDimension:0x600002b9a700 "UIView:0x7f9e6c423d50.height"> because they have no common ancestor.  Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'

I've tried creating these constraints using the following ways:

1.

let heightConstraint = NSLayoutConstraint(item: view1,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: view2,
                                          attribute: .height,
                                          multiplier: 1,
                                          constant: 0)
NSLayoutConstraint.activate([heightConstraint])

2.

let heightConstraint = NSLayoutConstraint(item: view1,
                                          attribute: .height,
                                          relatedBy: .equal,
                                          toItem: view2,
                                          attribute: .height,
                                          multiplier: 1,
                                          constant: 0)
horizontalStackView.addConstraint(heightConstraint)

where horizontalStackView is the horizontal stackview that holds all vertical stackviews.

I cannot figure out where this constraints were added to work through interface builder to create them through code.

Body:
Here is how you can get the above UI using code,

1. Create the UIView's with relevant backgroundColors,

    let v1 = UIView()
    v1.backgroundColor = #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1)
    v1.translatesAutoresizingMaskIntoConstraints = false

    let v2 = UIView()
    v2.backgroundColor = #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
    v2.translatesAutoresizingMaskIntoConstraints = false

    let v3 = UIView()
    v3.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
    v3.translatesAutoresizingMaskIntoConstraints = false

    let v4 = UIView()
    v4.backgroundColor = #colorLiteral(red: 0.5058823824, green: 0.3372549117, blue: 0.06666667014, alpha: 1)
    v4.translatesAutoresizingMaskIntoConstraints = false

    let v5 = UIView()
    v5.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
    v5.translatesAutoresizingMaskIntoConstraints = false

    let v6 = UIView()
    v6.backgroundColor = #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1)
    v6.translatesAutoresizingMaskIntoConstraints = false

    let v7 = UIView()
    v7.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
    v7.translatesAutoresizingMaskIntoConstraints = false

    let v8 = UIView()
    v8.backgroundColor = #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)
    v8.translatesAutoresizingMaskIntoConstraints = false

    let v9 = UIView()
    v9.backgroundColor = #colorLiteral(red: 0.06274510175, green: 0, blue: 0.1921568662, alpha: 1)
    v9.translatesAutoresizingMaskIntoConstraints = false

2. Create the horizontalStackViews with the above created UIViews. Don't forget to set the distribution as fillEqually

    let hStack1 = UIStackView(arrangedSubviews: [v1, v2, v3])
    hStack1.axis = .horizontal
    hStack1.distribution = .fillEqually
    hStack1.translatesAutoresizingMaskIntoConstraints = false

    let hStack2 = UIStackView(arrangedSubviews: [v4, v5, v6])
    hStack2.axis = .horizontal
    hStack2.distribution = .fillEqually
    hStack2.translatesAutoresizingMaskIntoConstraints = false

    let hStack3 = UIStackView(arrangedSubviews: [v7, v8, v9])
    hStack3.axis = .horizontal
    hStack3.distribution = .fillEqually
    hStack3.translatesAutoresizingMaskIntoConstraints = false

3. Create the verticalStackView using the above created horizontalStackViews and set its distribution as fillEqually as well

    let vStack = UIStackView(arrangedSubviews: [hStack1, hStack2, hStack3])
    vStack.axis = .vertical
    vStack.distribution = .fillEqually
    vStack.translatesAutoresizingMaskIntoConstraints = false

4. Add the vStack the controller's view,

    self.view.addSubview(vStack)

5. Add the below constraints to the vStack,

    vStack.heightAnchor.constraint(equalToConstant: 200).isActive = true
    vStack.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    vStack.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    vStack.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

Screenshot:


问:
How to copy value from SAP Tree View to Excel sheet using excel VBA
I want to copy the selected stock value of material in Excel sheet from SAP "MMBE" transaction:

If some one could help with the excel VBA syntax to copy the highlighted value in the attached snap.

答:
It is hard to predict column numbers and names although you can record your script with build in SAP recorder and just click proper cell twice to know what indexes it have.
It will get more and more complicated if your tables differ from each other. You will need to first get column names you are interested in, then compare it to keys etc.
Try to use SAP gui scripting help file, it is right below "SAP scripting and playback" menu option.</p>

```<code>Public SapGuiAuto
Public SetApp
Public Connection
Public session
Public theCell As String 'may be of anything else you need if casted properly

Sub example()

    Dim nameConstructor As String
    nameConstructor = "          "

    Set SapGuiAuto = GetObject("SAPGUI")
    Set SetApp = SapGuiAuto.GetScriptingEngine
    Set Connection = SetApp.Children(0)
    Set session = Connection.Children(0)

    theCell = session.findById("wnd[0]/usr/cntlCC_CONTAINER/shellcont/shell/shellcont[1]/shell[1]").GetItemText(nameConstructor & "6", "C" & nameConstructor & "1")
    MsgBox theCell
    Cells(1, 1) = theCell

End Sub
</code>```

Body:
It is hard to predict column numbers and names although you can record your script with build in SAP recorder and just click proper cell twice to know what indexes it have.
It will get more and more complicated if your tables differ from each other. You will need to first get column names you are interested in, then compare it to keys etc.
Try to use SAP gui scripting help file, it is right below "SAP scripting and playback" menu option.

Public SapGuiAuto
Public SetApp
Public Connection
Public session
Public theCell As String 'may be of anything else you need if casted properly

Sub example()

    Dim nameConstructor As String
    nameConstructor = "          "

    Set SapGuiAuto = GetObject("SAPGUI")
    Set SetApp = SapGuiAuto.GetScriptingEngine
    Set Connection = SetApp.Children(0)
    Set session = Connection.Children(0)

    theCell = session.findById("wnd[0]/usr/cntlCC_CONTAINER/shellcont/shell/shellcont[1]/shell[1]").GetItemText(nameConstructor & "6", "C" & nameConstructor & "1")
    MsgBox theCell
    Cells(1, 1) = theCell

End Sub


问:
WPF WebBrowser-Control does not display content
in my WPF-Application, I use a WebBrowser-Control to display Web contents. I test it with the Google search. In the following, first some source code:

```<code><Canvas x:Name="LayoutRoot" Background="White">
       <WebBrowser x:Name="browser"
                            Width="494"
                            Height="293"
                            Canvas.Left="3"
                            Canvas.Top="162"/>

</Canvas>
</code>```

```<code>public EventSide()
{
    InitializeComponent();
    browser.Navigate(new Uri("http://www.google.de/"));
}
</code>```

Now it depends on the following issues:
The contents of the WebBrowser control is completely empty. I'm going with the mouse over the WebBrowser Control, changes at the top and the mouse-cursor to the text cursor and I get a Tooltip called search. This is the search field from the google page. This means that the information is available from the Web via my webbrowser control, but apparently can not be displayed.

In my main window, I set the AllowsTransparency-property to "True". If I reset it to "False", the contents are displayed in my web browser element. Since I need a separate window design, I am dependent on the AllowsTransparency property.

Had anyone ever had the same problem and has a proposed solution?

答:
I guess WebBrowser control is not loaded when you call navigate, try this

```<code>public EventSide()
{
    InitializeComponent();
    browser.Loaded += delegate
    {
        browser.Navigate(new Uri("http://www.google.de/"));
    }
}
</code>```

EDIT

Note that WebBrowser is old style(COM I guess) control and doesn't support styling, animating and AllowTransparency...

See here for more details

I think the only solution is to use 3rd part browsers like WPF 3D Chromium Browser if you really need it

Hope this helps

ContentLicense: CC BY-SA 3.0

Body:
in my WPF-Application, I use a WebBrowser-Control to display Web contents. I test it with the Google search. In the following, first some source code:

<Canvas x:Name="LayoutRoot" Background="White">
       <WebBrowser x:Name="browser"
                            Width="494"
                            Height="293"
                            Canvas.Left="3"
                            Canvas.Top="162"/>

</Canvas>

public EventSide()
{
    InitializeComponent();
    browser.Navigate(new Uri("http://www.google.de/"));
}

Now it depends on the following issues:
The contents of the WebBrowser control is completely empty. I'm going with the mouse over the WebBrowser Control, changes at the top and the mouse-cursor to the text cursor and I get a Tooltip called search. This is the search field from the google page. This means that the information is available from the Web via my webbrowser control, but apparently can not be displayed.

In my main window, I set the AllowsTransparency-property to "True". If I reset it to "False", the contents are displayed in my web browser element. Since I need a separate window design, I am dependent on the AllowsTransparency property.

Had anyone ever had the same problem and has a proposed solution?

Body:
I guess WebBrowser control is not loaded when you call navigate, try this

public EventSide()
{
    InitializeComponent();
    browser.Loaded += delegate
    {
        browser.Navigate(new Uri("http://www.google.de/"));
    }
}

EDIT

Note that WebBrowser is old style(COM I guess) control and doesn't support styling, animating and AllowTransparency...

See here for more details

I think the only solution is to use 3rd part browsers like WPF 3D Chromium Browser if you really need it

Hope this helps


问:
Rundeck job API: javax.net.ssl.SSLHandshakeException: no cipher suites in common
Upgraded from Rundeck 3.0.2 (API v30) to 3.2.1 (API v34). Yum/RPM install, RHEL 7.

I configured SSL following Rundeck documentation and modeling after my existing working installation. SSL works fine via the web, and works fine when I hit the job REST API using curl, however when our MuleSoft application hits the REST API, it's failing with a handshake_failure:

```<code>%% Initialized:  [Session-1, SSL_NULL_WITH_NULL_NULL]
qtp1539575645-26, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-1, SSL_NULL_WITH_NULL_NULL]
qtp1539575645-26, SEND TLSv1.2 ALERT:  fatal, description = handshake_failure
qtp1539575645-26, WRITE: TLSv1.2 Alert, length = 2
qtp1539575645-26, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common
</code>```

I confirmed that MuleSoft trusts the Rundeck server's cert. Previously I wasn't explicitly including/excluding any ciphersuites in my Rundeck ssl config, but I forced MuleSoft to use a particular suite, and then added that suite to /etc/sysconfig/rundeckd using the -Drundeck.jetty.connector.ssl.includedCipherSuites=(insert suite here) parameter, however we still receive the "no cipher suites in common" error.

Adding the -Djavax.net.debug=ssl parm to /etc/sysconfig/rundeckd adds the handshake details to service.log. I can see the list of excluded ciphersuites, but I don't see confirmation that it's including the one(s) I added. I do see the parm in the process details of the running JVM.

This feels like a client issue on MuleSoft's side, and we're reaching out to the vendor however I find it odd that when I explicitly include the cipher suite that the client is sending it still doesn't see one in common. Perhaps I'm using the -Drundeck.jetty.connector.ssl.includedCipherSuites incorrectly?

My /etc/sysconfig/rundeckd file that I'm testing with currently looks like this:

```<code>export RUNDECK_WITH_SSL=true
export RDECK_HTTPS_PORT=4443
RDECK_JVM_OPTS="-Drundeck.jaaslogin=true \
       -Djava.security.auth.login.config=/etc/rundeck/jaas-multiauth.conf \
       -Dloginmodule.name=multiauth \
       -Djavax.net.ssl.trustStore=/etc/rundeck/ssl/truststore \
       -Djavax.net.ssl.trustStoreType=jks \
       -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol \
       -Drundeck.jetty.connector.ssl.includedCipherSuites=TLS_RSA_WITH_AES_256_GCM_SHA384 \
       -Dorg.eclipse.jetty.util.ssl.LEVEL=DEBUG \
       -Djavax.net.debug=ssl"

</code>```

Any thoughts are appreciated!

答: The issue was that the client, MuleSoft, required that the Rundeck server's SSL certificate had the 'KeyUsage=digitalSignature' extension. Adding this extension resolved the problem.</p>

Body:
Upgraded from Rundeck 3.0.2 (API v30) to 3.2.1 (API v34). Yum/RPM install, RHEL 7.

I configured SSL following Rundeck documentation and modeling after my existing working installation. SSL works fine via the web, and works fine when I hit the job REST API using curl, however when our MuleSoft application hits the REST API, it's failing with a handshake_failure:

%% Initialized:  [Session-1, SSL_NULL_WITH_NULL_NULL]
qtp1539575645-26, fatal error: 40: no cipher suites in common
javax.net.ssl.SSLHandshakeException: no cipher suites in common
%% Invalidated:  [Session-1, SSL_NULL_WITH_NULL_NULL]
qtp1539575645-26, SEND TLSv1.2 ALERT:  fatal, description = handshake_failure
qtp1539575645-26, WRITE: TLSv1.2 Alert, length = 2
qtp1539575645-26, fatal: engine already closed.  Rethrowing javax.net.ssl.SSLHandshakeException: no cipher suites in common

I confirmed that MuleSoft trusts the Rundeck server's cert. Previously I wasn't explicitly including/excluding any ciphersuites in my Rundeck ssl config, but I forced MuleSoft to use a particular suite, and then added that suite to /etc/sysconfig/rundeckd using the -Drundeck.jetty.connector.ssl.includedCipherSuites=(insert suite here) parameter, however we still receive the "no cipher suites in common" error.

Adding the -Djavax.net.debug=ssl parm to /etc/sysconfig/rundeckd adds the handshake details to service.log. I can see the list of excluded ciphersuites, but I don't see confirmation that it's including the one(s) I added. I do see the parm in the process details of the running JVM.

This feels like a client issue on MuleSoft's side, and we're reaching out to the vendor however I find it odd that when I explicitly include the cipher suite that the client is sending it still doesn't see one in common. Perhaps I'm using the -Drundeck.jetty.connector.ssl.includedCipherSuites incorrectly?

My /etc/sysconfig/rundeckd file that I'm testing with currently looks like this:

export RUNDECK_WITH_SSL=true
export RDECK_HTTPS_PORT=4443
RDECK_JVM_OPTS="-Drundeck.jaaslogin=true \
       -Djava.security.auth.login.config=/etc/rundeck/jaas-multiauth.conf \
       -Dloginmodule.name=multiauth \
       -Djavax.net.ssl.trustStore=/etc/rundeck/ssl/truststore \
       -Djavax.net.ssl.trustStoreType=jks \
       -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol \
       -Drundeck.jetty.connector.ssl.includedCipherSuites=TLS_RSA_WITH_AES_256_GCM_SHA384 \
       -Dorg.eclipse.jetty.util.ssl.LEVEL=DEBUG \
       -Djavax.net.debug=ssl"

Any thoughts are appreciated!


问:
pm2 does not apply changes to ecosystem.config.js on restart or reload
I have the following ecosystem.config.js file for my application:

```<code>module.exports = {
  apps: [
    {
      name: 'Worker A',
      script: 'scripts/workerA.js',
      instances: 4,
      autorestart: true,
      watch: false,
      instance_var: 'INSTANCE_ID',
      max_memory_restart: '1G'
    },
    {
      name: 'Worker B',
      script: 'scripts/workerB.js',
      instances: 4,
      autorestart: true,
      watch: false,
      instance_var: 'INSTANCE_ID',
      max_memory_restart: '1G'
    }
  ]
}
</code>```

When the processes are started via pm2 start ecosystem.config.js everything is working fine. However, if I now change the instances of the applications to a different number (i.e. 8) and try to restart the processes via pm2 restart ecosystem.config.js, the same number of instances will be started as before. pm2 reload ecosystem.config.js and pm2 startOrReload ecosystem.config.js show the same behaviour.

The only way I have solved the problem is to completely delete all the processes with pm2 delete ecosystem.config.js and then start them all again. While this works, it robs me of the possiblity to use the "0-second-downtime" restart that pm2 reload ... offers.

Is there any solution to this? Thanks!

```<code>$ pm2 -v
4.2.3
</code>```

答:
scaling nodes only work in cluster mode in pm2 (https://pm2.keymetrics.io/docs/usage/cluster-mode/)

so add
exec_mode : "cluster" to your configuration

```<code>module.exports = {
  apps: [
    {
      name: 'Worker A',
      script: 'scripts/workerA.js',
      instances: 4,
      autorestart: true,
      watch: false,
      instance_var: 'INSTANCE_ID',
      max_memory_restart: '1G',
    exec_mode : "cluster"
    },
    {
      name: 'Worker B',
      script: 'scripts/workerB.js',
      instances: 4,
      autorestart: true,
      watch: false,
      instance_var: 'INSTANCE_ID',
      max_memory_restart: '1G',
    exec_mode : "cluster"
    }
  ]
}
</code>```

Body:
I have the following ecosystem.config.js file for my application:

module.exports = {
  apps: [
    {
      name: 'Worker A',
      script: 'scripts/workerA.js',
      instances: 4,
      autorestart: true,
      watch: false,
      instance_var: 'INSTANCE_ID',
      max_memory_restart: '1G'
    },
    {
      name: 'Worker B',
      script: 'scripts/workerB.js',
      instances: 4,
      autorestart: true,
      watch: false,
      instance_var: 'INSTANCE_ID',
      max_memory_restart: '1G'
    }
  ]
}

When the processes are started via pm2 start ecosystem.config.js everything is working fine. However, if I now change the instances of the applications to a different number (i.e. 8) and try to restart the processes via pm2 restart ecosystem.config.js, the same number of instances will be started as before. pm2 reload ecosystem.config.js and pm2 startOrReload ecosystem.config.js show the same behaviour.

The only way I have solved the problem is to completely delete all the processes with pm2 delete ecosystem.config.js and then start them all again. While this works, it robs me of the possiblity to use the "0-second-downtime" restart that pm2 reload ... offers.

Is there any solution to this? Thanks!

$ pm2 -v
4.2.3

Body:
scaling nodes only work in cluster mode in pm2 (https://pm2.keymetrics.io/docs/usage/cluster-mode/)

so add
exec_mode : "cluster" to your configuration

module.exports = {
  apps: [
    {
      name: 'Worker A',
      script: 'scripts/workerA.js',
      instances: 4,
      autorestart: true,
      watch: false,
      instance_var: 'INSTANCE_ID',
      max_memory_restart: '1G',
    exec_mode : "cluster"
    },
    {
      name: 'Worker B',
      script: 'scripts/workerB.js',
      instances: 4,
      autorestart: true,
      watch: false,
      instance_var: 'INSTANCE_ID',
      max_memory_restart: '1G',
    exec_mode : "cluster"
    }
  ]
}


问:
Android Wear emulator goes into Ambient Mode automatically
I've been absent for some times from WearOS development. Now I am back and I have one annoying issue with the latest emulator - it goes automatically in Ambient Mode after few seconds. Not just my app, but the OS itself.

I Checked into the settings, tried clicking on the top of the window, but no luck - is there a settings for this or I should file a bug?

答:
Set the emulator to be charging.

Make sure Settings - Developer options - Stay awake when charging is enabled.(default)

PS: Click Settings - System - About - Build number quickly to enable Developer options.


问:
Adding values with condition in google bigquery
I need to add some values with a condition in GoogleBigQuery

NOTICE: I edited the original question since  it was not accurate enough.

Thanks to the two participants who have tried to help me.
I tried to apply the solutions  kindly suggested by you but I got the same result from the pct column as a result.

Something like this:
results

Here is the more detailed definition:

TABLE

Columns:

Shop: Shop location

brand: Brands of cars sold at shoplocation

sales: sales of each brand sold at each shop_location
rank: Rank of each brand per shop location (the biggest the greater)

total_sales_shop: SUM of all brand sales per shop location

pct: percentage of sales by brand in relationship with shop location
pct_acc:

What i need to calc is pct_acc which is the cumulative sum of the shops by rank (while it has no relation with brand)

PCT_ACC

My need is to reach something like PCT_ACC, and  then save the results in another one like this:endtable

答:
You can use following query to get the required data:

```<code>select values, rank,
sum(case when rank<2 then values else 0 end) condition1

from table
group by values, rank
</code>```

Need to add/remove columns from select and group by as per requirement

To get the cumulative sum you can use following query:

```<code>select shop, brand, sales, rank, total_sales_shop, pct ,
sum(pct) over (partition by shop order by rank) as pct_act
from data
</code>```

And to get the final table you can use combination of case statement and group by

e.g

```<code>select shop,
max(case when rank=1 then pct_act end) as rank_1,
max(case when rank=2 then pct_act end) as rank_2,
max(case when rank=3 then pct_act end) as rank_3,
max(case when rank=4 then pct_act end) as rank_4,
max(case when rank=5 then pct_act end) as rank_5
from cumulative_sum
group by shop
</code>```

Body:
You can use following query to get the required data:

select values, rank,
sum(case when rank<2 then values else 0 end) condition1

from table
group by values, rank

Need to add/remove columns from select and group by as per requirement

To get the cumulative sum you can use following query:

select shop, brand, sales, rank, total_sales_shop, pct ,
sum(pct) over (partition by shop order by rank) as pct_act
from data

And to get the final table you can use combination of case statement and group by

e.g

select shop,
max(case when rank=1 then pct_act end) as rank_1,
max(case when rank=2 then pct_act end) as rank_2,
max(case when rank=3 then pct_act end) as rank_3,
max(case when rank=4 then pct_act end) as rank_4,
max(case when rank=5 then pct_act end) as rank_5
from cumulative_sum
group by shop


问:
How do you fight design complexity?
I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.

It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our  engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.

And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.

We've all heard the refrain: Keep It Simple, Stupid™.

How do you fight with overcomplexity in your team?

One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.

答: I try to be open when discussing matters. But when i am discussing with someone else between something that seems simple and another one complicated, i get as stubborn as can be. It helps quite a lot, so long as you are very coherent from one decision to another.</p>

OwnerDisplayName: ʞɔıu

ContentLicense: CC BY-SA 2.5

Title: How do you fight design complexity?

LastEditorDisplayName: philippe

OwnerDisplayName: Benoît


问:
Error while executing sql script!
I am defining a variable in "userdata.sql",its contents are

```<code>SET DEFINE ON;
DEFINE name = Gaurav
DEFINE today =10/10/2011 --variable that contain date value.
</code>```

==================================================================================

I am creating another file called xyz.sql

```<code>@userdata.sql
DECLARE
v_date DATE;
v_name varchar2(10);
BEGIN
v_date:='&today';
v_name:='&name';
dbms_output.put_line('name is '||v_name);
dbms_output.put_line('date is '||v_date);
end;
</code>```

On execution of xyz.sql its throwing an error
ora-01840 input value not long enough for date format.
Please suggest the solution to it.
The RDBMS i am using is ORACLE

答:
Change this line:

```<code>v_date:='&today';
</code>```

to:

```<code>v_date:=to_date('&today','DD/MM/YYYY');
</code>```

i.e. specify the date format (it could be 'MM/DD/YYYY' instead).

Title: Error while executing sql script!

Body:
I am defining a variable in "userdata.sql",its contents are

SET DEFINE ON;
DEFINE name = Gaurav
DEFINE today =10/10/2011 --variable that contain date value.

==================================================================================

I am creating another file called xyz.sql

@userdata.sql
DECLARE
v_date DATE;
v_name varchar2(10);
BEGIN
v_date:='&today';
v_name:='&name';
dbms_output.put_line('name is '||v_name);
dbms_output.put_line('date is '||v_date);
end;

On execution of xyz.sql its throwing an error
ora-01840 input value not long enough for date format.
Please suggest the solution to it.
The RDBMS i am using is ORACLE

Body:
Change this line:

v_date:='&today';

to:

v_date:=to_date('&today','DD/MM/YYYY');

i.e. specify the date format (it could be 'MM/DD/YYYY' instead).


问:
How to fix MSB8029: Intermediate directory or Output directory cannot reside under the Temporary directory in VS2013
Visual Studio complains with each compile about with
warning MSB8029: The Intermediate directory or Output directory cannot reside under the Temporary directory as it could lead to issues with incremental build.

I was checking the projects and changed Output Directory and Intermediate Directory but I still got the message for each project in my solution.

How can I fix this?

答:
For those who run across this issue using VS 2019 (and possibly latter).
(It has nothing to do with TEMP environment variable).

VS 2019 does not support user settings and you should use project settings to disable warnings.
Knowing that MSBuild evaluates properties from environment too, you could define environment variable with same name as MSBuild property. Create following property in session where you would like to disable warning

set IgnoreWarnIntDirInTempDetected=true

and start build.


问:
URL decoding: UnsupportedEncodingException in Java
What I understand from the documentation is that UnsupportedEncodingException can only be thrown if I specify a wrong encoding as the second parameter to URLDecoder.decode(String, String) method. Is it so? I need to know cases where this exception can be thrown.

Basically, I have this code segment in one of my functions:

```<code>if (keyVal.length == 2) {
    try {
        value = URLDecoder.decode(
            keyVal[1],
            "UTF-8");
    } catch (UnsupportedEncodingException e) {
          // Will it ever be thrown?
    }
}
</code>```

Since I am explicitly mentioning "UTF-8", is there any way this exception can be thrown? Do I need to do anything in the catch block? Or, if my understanding is completely wrong, please let me know.

答:
That's because of the odd choice to make UnsupportedEncodingException checked. No, it won't be thrown.

I usually do as follows:

```<code>} catch (UnsupportedEncodingException e) {
  throw new AssertionError("UTF-8 not supported");
}
</code>```

Body:
What I understand from the documentation is that UnsupportedEncodingException can only be thrown if I specify a wrong encoding as the second parameter to URLDecoder.decode(String, String) method. Is it so? I need to know cases where this exception can be thrown.

Basically, I have this code segment in one of my functions:

if (keyVal.length == 2) {
    try {
        value = URLDecoder.decode(
            keyVal[1],
            "UTF-8");
    } catch (UnsupportedEncodingException e) {
          // Will it ever be thrown?
    }
}

Since I am explicitly mentioning "UTF-8", is there any way this exception can be thrown? Do I need to do anything in the catch block? Or, if my understanding is completely wrong, please let me know.

Body:
That's because of the odd choice to make UnsupportedEncodingException checked. No, it won't be thrown.

I usually do as follows:

} catch (UnsupportedEncodingException e) {
  throw new AssertionError("UTF-8 not supported");
}


问:
schema registry docker from confluent
I want to use the schema registry docker (image owned by confluent) with my open-source Kafka I installed locally on my PC.

I am using the following command to run the image :

```<code>docker run -p 8081:8081  \
    -e  SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS=PLAINTEXT://127.0.0.1:9092 \
    -e SCHEMA_REGISTRY_LISTENERS=http://0.0.0.0:8081 \
    -e SCHEMA_REGISTRY_DEBUG=true confluentinc/cp-schema-registry:latest
</code>```

but I am getting the following connection errors:

```<code>[kafka-admin-client-thread | adminclient-1] WARN org.apache.kafka.clients.NetworkClient - [AdminClient clientId=adminclient-1] Connection to node -1 (/127.0.0.1:9092) could not be established. Broker may not be available.
[kafka-admin-client-thread | adminclient-1] WARN org.apache.kafka.clients.NetworkClient - [AdminClient clientId=adminclient-1] Connection to node -1 (/127.0.0.1:9092) could not be established. Broker may not be available.
[main] ERROR io.confluent.admin.utils.ClusterStatus - Error while getting broker list.
java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment.
    at org.apache.kafka.common.internals.KafkaFutureImpl.wrapAndThrow(KafkaFutureImpl.java:45)
    at org.apache.kafka.common.internals.KafkaFutureImpl.access$000(KafkaFutureImpl.java:32)
    at org.apache.kafka.common.internals.KafkaFutureImpl$SingleWaiter.await(KafkaFutureImpl.java:89)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:260)
    at io.confluent.admin.utils.ClusterStatus.isKafkaReady(ClusterStatus.java:149)
    at io.confluent.admin.utils.cli.KafkaReadyCommand.main(KafkaReadyCommand.java:150)
Caused by: org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment.
[main] INFO io.confluent.admin.utils.ClusterStatus - Expected 1 brokers but found only 0. Trying to query Kafka for metadata again ...
</code>```

I have Kafka installed on my localhost.
Any idea to solve this, please?

答:
I have Kafka installed on my localhost

As commented, localhost is unclear when you're actually using multiple machines (one physical and at least one virtual)

You need to use host.docker.internal:9092

https://docs.docker.com/docker-for-windows/networking/ (removed because host is not windows)

On a Linux host, you need to use host networking mode

https://docs.docker.com/network/host/

Although, realistically, running Kafka in a container would be simpler for connecting the two

Title: schema registry docker from confluent

Body:
I want to use the schema registry docker (image owned by confluent) with my open-source Kafka I installed locally on my PC.

I am using the following command to run the image :

docker run -p 8081:8081  \
    -e  SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS=PLAINTEXT://127.0.0.1:9092 \
    -e SCHEMA_REGISTRY_LISTENERS=http://0.0.0.0:8081 \
    -e SCHEMA_REGISTRY_DEBUG=true confluentinc/cp-schema-registry:latest

but I am getting the following connection errors:

[kafka-admin-client-thread | adminclient-1] WARN org.apache.kafka.clients.NetworkClient - [AdminClient clientId=adminclient-1] Connection to node -1 (/127.0.0.1:9092) could not be established. Broker may not be available.
[kafka-admin-client-thread | adminclient-1] WARN org.apache.kafka.clients.NetworkClient - [AdminClient clientId=adminclient-1] Connection to node -1 (/127.0.0.1:9092) could not be established. Broker may not be available.
[main] ERROR io.confluent.admin.utils.ClusterStatus - Error while getting broker list.
java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment.
    at org.apache.kafka.common.internals.KafkaFutureImpl.wrapAndThrow(KafkaFutureImpl.java:45)
    at org.apache.kafka.common.internals.KafkaFutureImpl.access$000(KafkaFutureImpl.java:32)
    at org.apache.kafka.common.internals.KafkaFutureImpl$SingleWaiter.await(KafkaFutureImpl.java:89)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:260)
    at io.confluent.admin.utils.ClusterStatus.isKafkaReady(ClusterStatus.java:149)
    at io.confluent.admin.utils.cli.KafkaReadyCommand.main(KafkaReadyCommand.java:150)
Caused by: org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment.
[main] INFO io.confluent.admin.utils.ClusterStatus - Expected 1 brokers but found only 0. Trying to query Kafka for metadata again ...

I have Kafka installed on my localhost.
Any idea to solve this, please?


问:
jsx console log inside map inside return statement
I'm working inside a stateless function controller in React. I'm trying to do a console.log inside a map that is inside a return statement.
This works:

```<code>{options.map(o => (
   {console.log(o)}
))}
</code>```

And this works:

```<code>return (
   <>
      //more html/jsx code
      {console.log("test")}
      //more html/jsx code
   </>
)
</code>```

But how to log inside a map that is inside a return statement? like so:

```<code>return (
   //more html/jsx code
   {options.map(o => (
      <>
         {console.log(o)} //doesn't compile
         console.log(o) //doesn't work -> written in DOM
      </>
   ))}
   //more html/jsx code
)

</code>```

Anyone have an idea if this is possibly at all. I find many answers articles/questions where they do 1 of the 2. Or in a map or in a return statement. Can't seem to find an answer that is both in a return statement and a map. I, ofcourse, only use console.log for testing purposes

答:
You are still able to console inside the map function.
But you should put console.log out of return JSX element.

```<code>const array = ['test', 'item2', 'item3'];
array.map(item => {
  console.log(item) // put your console here.
  return (
    <>{item}</>
  )
})
</code>```

This will be duplicated with this question

Body:
I'm working inside a stateless function controller in React. I'm trying to do a console.log inside a map that is inside a return statement.
This works:

{options.map(o => (
   {console.log(o)}
))}

And this works:

return (
   <>
      //more html/jsx code
      {console.log("test")}
      //more html/jsx code
   </>
)

But how to log inside a map that is inside a return statement? like so:

return (
   //more html/jsx code
   {options.map(o => (
      <>
         {console.log(o)} //doesn't compile
         console.log(o) //doesn't work -> written in DOM
      </>
   ))}
   //more html/jsx code
)

Anyone have an idea if this is possibly at all. I find many answers articles/questions where they do 1 of the 2. Or in a map or in a return statement. Can't seem to find an answer that is both in a return statement and a map. I, ofcourse, only use console.log for testing purposes

Body:
You are still able to console inside the map function.
But you should put console.log out of return JSX element.

const array = ['test', 'item2', 'item3'];
array.map(item => {
  console.log(item) // put your console here.
  return (
    <>{item}</>
  )
})

This will be duplicated with this question


问:
Associated tags in an Azure DevOps release
Is there a way to retrieve the list of tags associated to a specific release while running (e.g. within a PowerShell task)?

I searched in the predefined variables, but I could not find anything about it.

I could also get the information using the REST API, but I would like to avoid redundant work.

答:
For release pipeline, you can find related variables here.

I think you can use Release.Artifacts.{alias}.SourceVersion to get closest commit for your release. And then you can use some git command to get tags the commit has.

For me, I use something like this in Command Line task:

```<code>echo Get the tags.
git tag --points-at $(Release.Artifacts._GithubPermissionTest.SourceVersion
</code>```

Result in log:

It do output the tags the commit has. And you can also do similar job in PS task.

Also, if you want to get tags from build instead of release, you can refer to this. Hope it helps.

Body:
For release pipeline, you can find related variables here.

I think you can use Release.Artifacts.{alias}.SourceVersion to get closest commit for your release. And then you can use some git command to get tags the commit has.

For me, I use something like this in Command Line task:

echo Get the tags.
git tag --points-at $(Release.Artifacts._GithubPermissionTest.SourceVersion

Result in log:

It do output the tags the commit has. And you can also do similar job in PS task.

Also, if you want to get tags from build instead of release, you can refer to this. Hope it helps.


问:
How can I add raw data body to an axios request?
I am trying to communicate with an API from my React application using Axios. I managed to get the GET request working, but now I need a POST one.

I need the body to be raw text, as I will write an MDX query in it. Here is the part where I make the request:

```<code>axios.post(baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
    {
      headers: { 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
      'Content-Type' : 'text/plain' }
    }).then((response) => {
      this.setState({data:response.data});
      console.log(this.state.data);
    });
</code>```

Here I added the content type part. But how can I add the body part?

Thank you.

Edit:

Here is a screenshot of the working Postman request

答:
There many methods to send raw data with a post request. I personally like this one.

```<code>    const url = "your url"
    const data = {key: value}
    const headers = {
        "Content-Type": "application/json"
    }
    axios.post(url, data, headers)
</code>```

Body:
I am trying to communicate with an API from my React application using Axios. I managed to get the GET request working, but now I need a POST one.

I need the body to be raw text, as I will write an MDX query in it. Here is the part where I make the request:

axios.post(baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
    {
      headers: { 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx',
      'Content-Type' : 'text/plain' }
    }).then((response) => {
      this.setState({data:response.data});
      console.log(this.state.data);
    });

Here I added the content type part. But how can I add the body part?

Thank you.

Edit:

Here is a screenshot of the working Postman request

Body:
There many methods to send raw data with a post request. I personally like this one.

    const url = "your url"
    const data = {key: value}
    const headers = {
        "Content-Type": "application/json"
    }
    axios.post(url, data, headers)


问:
Read JSON file through Shell Script & replace keys
I am a newbie to Shell Script, I need to read a local JSON file through shell script and want to find & replace all the keys.

JSON File

```<code>{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}
</code>```

shell-script.sh

```<code>path="./path.json"
# arr=("key1" "key2" "key3")   // this works fine
mapfile -t arr < <(./jq -r 'keys[]' $path) // not working

for elem in "${arr[@]}"
do
sed -i "s/${elem}/MyNewKey/g" $path
done
</code>```

Here, what is the difference between a hard coded array & the array generated from mapfile utility?

If I echo arr in both the ways, both are looks same in console.

Can someone helps me to understand what is the difference?

答:
Try sed -i "s/$elem/MyNewKey/g" $path

You have to reference elem that way, because its not an array. It is a specific element of your array. Generally you reference a for-loop variable by putting a $ infront of it.

For simple examples regarding for loops i found this to be helpful.

Body:
I am a newbie to Shell Script, I need to read a local JSON file through shell script and want to find & replace all the keys.

JSON File

{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

shell-script.sh

path="./path.json"
# arr=("key1" "key2" "key3")   // this works fine
mapfile -t arr < <(./jq -r 'keys[]' $path) // not working

for elem in "${arr[@]}"
do
sed -i "s/${elem}/MyNewKey/g" $path
done

Here, what is the difference between a hard coded array & the array generated from mapfile utility?

If I echo arr in both the ways, both are looks same in console.

Can someone helps me to understand what is the difference?


问:
Pasting image from clipboard in Angular doesn't work
I'm trying to retrieve the Files elements from the ClipboardEvent in Angular when copy/pasting an image to a textaera.

Using the (paste)="onPaste($event)" binding, when looking to the console I only get back empty files array:

Here is the stackblitz example to reproduce the issue.

答:
Don't care about the console log. it's just a bug with the console.

Try this :

```<code>onPaste(e: any ) {
    const items = (e.clipboardData || e.originalEvent.clipboardData).items;
    let blob = null;
    for (const item of items) {
      if (item.type.indexOf('image') === 0) {
        blob = item.getAsFile();
        console.log(blob); // Prints your files
      }
    }
}
</code>```

Stackblitz Example : Link

PS : If you want the "name" of pasted items, you'll need to solicit input from the user. because Clipboard API doesn't support it

Body:
Don't care about the console log. it's just a bug with the console.

Try this :

onPaste(e: any ) {
    const items = (e.clipboardData || e.originalEvent.clipboardData).items;
    let blob = null;
    for (const item of items) {
      if (item.type.indexOf('image') === 0) {
        blob = item.getAsFile();
        console.log(blob); // Prints your files
      }
    }
}

Stackblitz Example : Link

PS : If you want the "name" of pasted items, you'll need to solicit input from the user. because Clipboard API doesn't support it


问:
Razor to produce single line text
I want to write Razor view helper to produce single line content:

```<code>@helper Format(obj) {
   <text>
       @obj.Title
       @obj.FormatInnerData() (obj.User != null)
       {
          @obj.User.Name
       }
   <text>
}
</code>```

But of course I get

```<code>Title
Inner Data
User Name
</code>```

Currently I have to do

```<code><text>@obj.Title @obj.FormatInnerData() @(obj.User != null ? obj.User.Name : "")</text>
</code>```

to produce text output as single line without line breaks, but this can grow quite long / unreadable for many properties.

In other words, how do I more conveniently use Razor to generate text content, not markup content?

UPD: Ideally that would be something like

```<code>   <content>@obj.Title</content>
   <content>@obj.Format()
 @obj.User.Name</content>
</code>```

i.e. only parts between content tags go into output stream. Of course maybe a simpler syntax, like @: instead of <text>.

An example use case would be to generate JavaScript string content with markup inside, or, generate text files with license details in format "Key: Name (details)" on each line, padded with spaces for grouping.

答:
So if I understand you correctly, you would like a way to specify your views with multiple lines, while the eventual output would be everything on one line?

I don't think that's possible out of the box, but you could write your own Custom RazorViewEngine (derived from the actual RazorViewEngine), which trims out all the newlines before returning the view.

Title: Razor to produce single line text

Body:
I want to write Razor view helper to produce single line content:

@helper Format(obj) {
   <text>
       @obj.Title
       @obj.FormatInnerData() (obj.User != null)
       {
          @obj.User.Name
       }
   <text>
}

But of course I get

Title
Inner Data
User Name

Currently I have to do

<text>@obj.Title @obj.FormatInnerData() @(obj.User != null ? obj.User.Name : "")</text>

to produce text output as single line without line breaks, but this can grow quite long / unreadable for many properties.

In other words, how do I more conveniently use Razor to generate text content, not markup content?

UPD: Ideally that would be something like

   <content>@obj.Title</content>
   <content>@obj.Format()
 @obj.User.Name</content>

i.e. only parts between content tags go into output stream. Of course maybe a simpler syntax, like @: instead of <text>.

An example use case would be to generate JavaScript string content with markup inside, or, generate text files with license details in format "Key: Name (details)" on each line, padded with spaces for grouping.


问:
setting double quotes around lowercase oracle database names
we have oracle databases with names and columns in lowercase and we need a way to handle this problem, because without double quotes around the lowercase identifiers, Informatica PowerCenter doesn't find those tables.  Is there an option in oracle that sets every identifier in double quotes automatically before executing a query?</p>

答:
Is there an option in oracle that sets every identifier in double quotes automatically before executing a query?

No, you either need to use:

double quotes around every identifier;

rename the tables and columns so they aren't defined using lower-case characters; or

create views of your tables that have upper-case identifiers for the table name and columns so that Oracle's default behaviour (of converting every unquoted identifier to upper-case) can be used.


问:
Is there an established name for this anti-pattern?
Quite often I see code that use redundant properties for data, when one value could have been calculated on the fly from two others. To me it is an obvious anti-pattern, as it makes further work on the code much harder. Every time you change one value you are expected to know how it relates to other values and change those too. If you mess this up, there is an ambiguous situation where you don't know what values are correct and what aren't.

However, I don't know if this is a "known" anti-pattern with an established name.

# Bad
class Rectangle
  attr_accessor: height
  attr_accessor: width
  attr_accessor: ratio

  def initialize
    @height = 1
    @width = 1
    @ratio = 1
  end
end

# Good
class Rectangle
  attr_accessor: height
  attr_accessor: width

  def initialize
    @height = 1
    @width = 1
  end

  def ratio
   @width.to_f / @height
  end
end
```

答:
Basically a violation of don't repeat yourself?

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

Violations of DRY are typically referred to as WET solutions, which is commonly taken to stand for "write every time", "write everything twice", "we enjoy typing" or "waste everyone's time".


问:
Data from array to sheet
I have an array that plots data to a messagebox, how can I also have that same data on a different sheet?

The data I am working with is a linear cable cut list. It looks at the total cable length and the individual lengths and checks to see how many reels of cable I need for all the separate individual lengths.

Ideally Reel 1 lengths would go in column A and the next reel would be column B, so on and so forth with a blank column in between the different cable types.

```<code>    'Message Box Output
    For k = LBound(DetStk, 2) To UBound(DetStk, 2)
       sMsg = sMsg & DetStk(1, k) & vbTab & vbTab _
            & DetStk(0, k) & vbCrLf
    Next k
</code>```

THIS IS WHAT I GOT WORKING WITH HELP FROM "Splintered-Origins-Dev"

```<code>    'Sheet Output
    n = 3
    q = rC + p - 6
    For k = LBound(DetStk, 2) To UBound(DetStk, 2)
        If k - 1 >= LBound(DetStk, 2) Then
            If DetStk(0, k - 1) <> DetStk(0, k) Then
                'Data line reset
                n = 3
                p = p + 1
                q = rC + p - 6
                wsVG.Cells(1, q).Value2 = cblType
                wsVG.Cells(2, q).Value2 = DetStk(0, k) & " Reels"
            End If
        Else
            wsVG.Cells(1, q).Value2 = cblType
            wsVG.Cells(2, q).Value2 = DetStk(0, k) & " Reels"
        End If
        wsVG.Cells(n, q).Value2 = DetStk(1, k)
        n = n + 1
    Next k
</code>```

答:
It's not pretty or elegant, but the following code will allow you to output the data going to your message box to a new sheet "Reel Data". Just replace "loopvar" with whatever variable you're using to iterate through each loop. Additionally the "- 1" in the q variable for columns may or may not be needed depending on how your loop variable is set up. I also recommend adding someplace at the beginning of the sub Worksheets("Reel Data").Cells.Clear to wipe out any old data left behind by previous runs and p = 0 to reset the column counter.

```<code>    n = 3 'Row
    q = *loopvar* + p - 1 'Column
    For k = LBound(DetStk, 2) To UBound(DetStk, 2)
        If k - 1 >= LBound(DetStk, 2) Then 'If reel count changes, move over a column
            If DetStk(0, k - 1) <> DetStk(0, k) Then
                n = 3 'Row reset
                p = p + 1 'Increment Column
                q = *loopvar* + p - 1
                Worksheets("Reel Data").Cells(2, q).Value2 = DetStk(0, k)
            End If
        Else
            Worksheets("Reel Data").Cells(2, q).Value2 = DetStk(0, k) 'First Reel
        End If
        Worksheets("Reel Data").Cells(n, q).Value2 = DetStk(1, k)
        n = n + 1 ' Increment Row
    Next k
    p = p + 1 'This will add an extra column before the next iteration
</code>```

Title: Data from array to sheet

Body:
I have an array that plots data to a messagebox, how can I also have that same data on a different sheet?

The data I am working with is a linear cable cut list. It looks at the total cable length and the individual lengths and checks to see how many reels of cable I need for all the separate individual lengths.

Ideally Reel 1 lengths would go in column A and the next reel would be column B, so on and so forth with a blank column in between the different cable types.

    'Message Box Output
    For k = LBound(DetStk, 2) To UBound(DetStk, 2)
       sMsg = sMsg & DetStk(1, k) & vbTab & vbTab _
            & DetStk(0, k) & vbCrLf
    Next k

THIS IS WHAT I GOT WORKING WITH HELP FROM "Splintered-Origins-Dev"

    'Sheet Output
    n = 3
    q = rC + p - 6
    For k = LBound(DetStk, 2) To UBound(DetStk, 2)
        If k - 1 >= LBound(DetStk, 2) Then
            If DetStk(0, k - 1) <> DetStk(0, k) Then
                'Data line reset
                n = 3
                p = p + 1
                q = rC + p - 6
                wsVG.Cells(1, q).Value2 = cblType
                wsVG.Cells(2, q).Value2 = DetStk(0, k) & " Reels"
            End If
        Else
            wsVG.Cells(1, q).Value2 = cblType
            wsVG.Cells(2, q).Value2 = DetStk(0, k) & " Reels"
        End If
        wsVG.Cells(n, q).Value2 = DetStk(1, k)
        n = n + 1
    Next k

Body:
It's not pretty or elegant, but the following code will allow you to output the data going to your message box to a new sheet "Reel Data". Just replace "loopvar" with whatever variable you're using to iterate through each loop. Additionally the "- 1" in the q variable for columns may or may not be needed depending on how your loop variable is set up. I also recommend adding someplace at the beginning of the sub Worksheets("Reel Data").Cells.Clear to wipe out any old data left behind by previous runs and p = 0 to reset the column counter.

    n = 3 'Row
    q = *loopvar* + p - 1 'Column
    For k = LBound(DetStk, 2) To UBound(DetStk, 2)
        If k - 1 >= LBound(DetStk, 2) Then 'If reel count changes, move over a column
            If DetStk(0, k - 1) <> DetStk(0, k) Then
                n = 3 'Row reset
                p = p + 1 'Increment Column
                q = *loopvar* + p - 1
                Worksheets("Reel Data").Cells(2, q).Value2 = DetStk(0, k)
            End If
        Else
            Worksheets("Reel Data").Cells(2, q).Value2 = DetStk(0, k) 'First Reel
        End If
        Worksheets("Reel Data").Cells(n, q).Value2 = DetStk(1, k)
        n = n + 1 ' Increment Row
    Next k
    p = p + 1 'This will add an extra column before the next iteration


答:
Here's a simple way which only has a small amount of Python looping and a lot of vectorized work:

```<code>x, y = c[:,0], c[:,1]
for i in -1,0,1:
    for j in -1,0,1:
        field[x+i,y+j] = 1
</code>```

A more complicated way which may be faster:

```<code>offsets = np.array([[-1,-1],[-1,0],[-1,1], [0,-1],[0,0],[0,1], [1,-1],[1,0],[1,1]])
fill = (offsets + c[:,None]).reshape(-1,2)
field[fill[:,0], fill[:,1]] = 1
</code>```

Title: Setting a surrounding block based on center index in a numpy array

Body:
I have a 2D numpy array of zeros representing some flat surface:

field = np.zeros((10,10))

field
Out[165]:
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

Then I have an array of coordinates in the form [row,column] such as:

In [166]:c = np.array([[1,2],[4,5],[7,3],[2,6]])

In [167]:c
Out[167]:
array([[1, 2],
       [4, 5],
       [7, 3],
       [2, 6]])

What I would like to do is populate a block of the field array around the coordinates in c.

Out[192]:
array([[0., 1., 1., 1., 0., 0., 0., 0., 0., 0.],
       [0., 1., 1., 1., 0., 1., 1., 1., 0., 0.],
       [0., 1., 1., 1., 0., 1., 1., 1., 0., 0.],
       [0., 0., 0., 0., 1., 1., 1., 1., 0., 0.],
       [0., 0., 0., 0., 1., 1., 1., 0., 0., 0.],
       [0., 0., 0., 0., 1., 1., 1., 0., 0., 0.],
       [0., 0., 1., 1., 1., 0., 0., 0., 0., 0.],
       [0., 0., 1., 1., 1., 0., 0., 0., 0., 0.],
       [0., 0., 1., 1., 1., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

My initial attempt using numpy vectorization was:

In [168]:field[c[:,0]-1:c[:,0]+1,c[:,1]-1:c[:,1]+1] = 10
Traceback (most recent call last):

  File "<ipython-input-168-5433a2f4a5cf>", line 1, in <module>
    field[c[:,0]-1:c[:,0]+1,c[:,1]-1:c[:,1]+1] = 10

TypeError: only integer scalar arrays can be converted to a scalar index

I then tried first creating the c[:,0]-1 and c[:,1]+1 arrays before hand but got the same error which leads me to the conclusion that, that type of ranged indexing cannot be done in numpy.

I have also had a look at the np.ix_() but cannot set surrounding blocks of multiple coordinates without a for loop using this method.

I am able to achieve the desired output however using the for loop:

for row,column in c:
        field[row-1:row+2,column-1:column+2] = 1

But would not like to use a for loop because both c and f will be large and multidimensional in my final application and I feel I can capitalize on the speed improvements made by numpy vectorization.

Also, I know in image processing this could be seen as a dilation or erosion problem but I already have the coordinates for an erosion/dilation kernel to be placed at and again, multiple dimensions and very large arrays.

Body:
Here's a simple way which only has a small amount of Python looping and a lot of vectorized work:

x, y = c[:,0], c[:,1]
for i in -1,0,1:
    for j in -1,0,1:
        field[x+i,y+j] = 1

A more complicated way which may be faster:

offsets = np.array([[-1,-1],[-1,0],[-1,1], [0,-1],[0,0],[0,1], [1,-1],[1,0],[1,1]])
fill = (offsets + c[:,None]).reshape(-1,2)
field[fill[:,0], fill[:,1]] = 1


问:
Boxplotting Masked Arrays
How can i boxplot only the non-masked values of a MaskedArray ? I tought this would happen automatically by boxplot(ma) but this seems to boxplot the non-masked array.

答:
I think you are right -- plt.boxplot ignores the mask if sent a masked array.
So it looks like you'll have to give boxplot some extra help by sending it only the values which are not masked. Since each row of the array may have a different number of unmasked values, you won't be able to use a numpy array. You'll have to form a Python sequence of vectors:

```<code>z = [[y for y in row if y] for row in x.T]
</code>```

For example:

```<code>import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()

N=20
M=10

x = np.random.random((M,N))
mask=np.random.random_integers(0,1,N*M).reshape((M,N))
x = np.ma.array(x,mask=mask)
ax1=fig.add_subplot(2,1,1)
ax1.boxplot(x)

z = [[y for y in row if y] for row in x.T]
ax2=fig.add_subplot(2,1,2)
ax2.boxplot(z)
plt.show()
</code>```

Above, the first subplot shows a boxplot of all the data in x (ignoring the mask), and the second subplot shows a boxplot of only those values which are not masked.

Title: Boxplotting Masked Arrays

Body:
I think you are right -- plt.boxplot ignores the mask if sent a masked array.
So it looks like you'll have to give boxplot some extra help by sending it only the values which are not masked. Since each row of the array may have a different number of unmasked values, you won't be able to use a numpy array. You'll have to form a Python sequence of vectors:

z = [[y for y in row if y] for row in x.T]

For example:

import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()

N=20
M=10

x = np.random.random((M,N))
mask=np.random.random_integers(0,1,N*M).reshape((M,N))
x = np.ma.array(x,mask=mask)
ax1=fig.add_subplot(2,1,1)
ax1.boxplot(x)

z = [[y for y in row if y] for row in x.T]
ax2=fig.add_subplot(2,1,2)
ax2.boxplot(z)
plt.show()

Above, the first subplot shows a boxplot of all the data in x (ignoring the mask), and the second subplot shows a boxplot of only those values which are not masked.


问:
Why my decision tree have not node? (C5.0)
I have 204 data with 6 atribute.

When i create the model with all data with this script, model = C5.0(dataset1[,-7], dataset1[,7]),
the result give me no node like the picture below.

But, if i just use 100 data with this script, model = C5.0(dataset1[1:100,-7], dataset1[1:100,7]), the result give me a good decision tree like the picture below.

What is the problem? Is the problem in the data?
Thank you.

答:
Examining the display of your trees, it is easy to see that what happened.
The second model using only 100 points is NOT a better model that the first.
When you gave C5.0 more data, it correctly determined that a simpler model
was superior.   Look at the results.

The first tree (with all 204 points) predicts everything is Lancar giving
an error rate of 27% (55 errors out of 204).

What is the error rate for the second tree?

Node 2 predicts Lancar for 55 points with 25.5% errors (14 errors).

Node 4 predicts Lancar for 25 points with 28.0% errors ( 7 errors).

Node 6 predicts Macet  for 8 points with 50.0% errors ( 4 errors).

Node 7 predicts Macet  for 12 points with 41.7% errors ( 5 errors).

Total errors 30 out of 100 or 30.0% - worse than the 27% error rate
for the simpler model. C5.0 simply determined that the best model available was to predict that all points are in the majority class (Lancar).


问:
Maven compiler error - invalid flag -- release
I am getting a maven compiler error when compiling with JDK 1.8

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project DUMMY : Fatal error compiling: invalid flag: --release -> [Help 1]

Here is my pom configuration for compiler plugin

```<code>            <configuration>
                <source>${maven.compiler.release}</source>
                <target>${maven.compiler.release}</target>
                <release>${maven.compiler.release}</release>
                <jdkToolchain>
                    <version>${maven.compiler.release}</version>
                </jdkToolchain>
                <verbose>false</verbose>
                <useIncrementalCompilation>false</useIncrementalCompilation>
                <executable>${env.JAVA_HOME}/bin/javac</executable>
            </configuration>
</code>```

Have I configured this incorrectly? Also, this works fine when I have Java 11 for JAVA_HOME, but not with Java 8. Is this expected? Also, from the docs I see that maven.compiler.release is tied with release config anyway. So, does it mean I can ommit the release attribute below and it should be fine?

答: As mentioned in documentation this argument supported since Java 9, so either change your JDK version or just remove it.</p>

Body:
I am getting a maven compiler error when compiling with JDK 1.8

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project DUMMY : Fatal error compiling: invalid flag: --release -> [Help 1]

Here is my pom configuration for compiler plugin

            <configuration>
                <source>${maven.compiler.release}</source>
                <target>${maven.compiler.release}</target>
                <release>${maven.compiler.release}</release>
                <jdkToolchain>
                    <version>${maven.compiler.release}</version>
                </jdkToolchain>
                <verbose>false</verbose>
                <useIncrementalCompilation>false</useIncrementalCompilation>
                <executable>${env.JAVA_HOME}/bin/javac</executable>
            </configuration>

Have I configured this incorrectly? Also, this works fine when I have Java 11 for JAVA_HOME, but not with Java 8. Is this expected? Also, from the docs I see that maven.compiler.release is tied with release config anyway. So, does it mean I can ommit the release attribute below and it should be fine?


问:
Java Code to read file is not compiling on VS code editor
```<code>
import java.util.Scanner;
import java.io.*;
/*
 * PROJECT I: ReadData.java
 *
 * A sample code which demonstrates how to read data from an ASCII file using
 * the Scanner
 */

public class ReadData {

  public static void main(String[] args) {

    double x,y,rad;
    int lineCount = 0;

    //Initialise the max and minimum to something sensible
    double maxX = Double.MIN_VALUE;
    double minX = Double.MAX_VALUE;
    double maxY = Double.MIN_VALUE;
    double minY = Double.MAX_VALUE;
 try {
        File file = new File("C:\\Users\\Yakov\\Desktop\\Study stuff\\MA117\\Project 1.data");
      Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));

      while(scanner.hasNext()) {

        //Read the three valies on each line of the file
        x = scanner.nextDouble();
        y = scanner.nextDouble();
        rad = scanner.nextDouble();

        //Increment the linecounter.
        lineCount++;

        // Find max, min for x and y coords
        if (x > maxX) {
          maxX = x;
        }
        if (y > maxY) {
          maxY = y;
        }
        if (x < minX) {
            minX = x;
        }
        if (y < minY) {
          minY = y;
        }

      }
    } catch(Exception e) {
      System.err.println("An error has occured. See below for details");
      e.printStackTrace();
    }

    System.out.println("Information about the data:");
    System.out.println("  Number of lines in file: " + lineCount);

    System.out.format("  Max x-coord: %10.9f\n", maxX);
    System.out.format("  Min x-coord: %10.9f\n", minX);
    System.out.format("  Max y-coord: %10.9f\n", maxY);
    System.out.format("  Min y-coord: %10.9f\n", minY);

  }

}

</code>```

I'm trying to run this Java code in VS code editor. It is a sample code which is supposed to be able to run, which is provided on the internet. How do I make this run? Is there maybe a problem in this code? The file I have inserted in is real( it exists) , so I dont see any reason this code is not running. I am using windows. Any idea how to fix this? The error is "Exception in thread "main" java.lang.Error: Unresolved compilation problem:

```<code>    at ReadData.main(ReadData (1).java:24)"
</code>```

Edit: import of scanner is not the problem

答:
Your error is that you have violated the "first rule of Java":

Every class have to be saved in an file with identical name appended by .java.

Therefore the class ReadData have to be saved in a file named ReadData.java - not ReadData (1).java as you did.

Body:
import java.util.Scanner;
import java.io.*;
/*
 * PROJECT I: ReadData.java
 *
 * A sample code which demonstrates how to read data from an ASCII file using
 * the Scanner
 */

public class ReadData {

  public static void main(String[] args) {

    double x,y,rad;
    int lineCount = 0;

    //Initialise the max and minimum to something sensible
    double maxX = Double.MIN_VALUE;
    double minX = Double.MAX_VALUE;
    double maxY = Double.MIN_VALUE;
    double minY = Double.MAX_VALUE;
 try {
        File file = new File("C:\\Users\\Yakov\\Desktop\\Study stuff\\MA117\\Project 1.data");
      Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));

      while(scanner.hasNext()) {

        //Read the three valies on each line of the file
        x = scanner.nextDouble();
        y = scanner.nextDouble();
        rad = scanner.nextDouble();

        //Increment the linecounter.
        lineCount++;

        // Find max, min for x and y coords
        if (x > maxX) {
          maxX = x;
        }
        if (y > maxY) {
          maxY = y;
        }
        if (x < minX) {
            minX = x;
        }
        if (y < minY) {
          minY = y;
        }

      }
    } catch(Exception e) {
      System.err.println("An error has occured. See below for details");
      e.printStackTrace();
    }

    System.out.println("Information about the data:");
    System.out.println("  Number of lines in file: " + lineCount);

    System.out.format("  Max x-coord: %10.9f\n", maxX);
    System.out.format("  Min x-coord: %10.9f\n", minX);
    System.out.format("  Max y-coord: %10.9f\n", maxY);
    System.out.format("  Min y-coord: %10.9f\n", minY);

  }

}

I'm trying to run this Java code in VS code editor. It is a sample code which is supposed to be able to run, which is provided on the internet. How do I make this run? Is there maybe a problem in this code? The file I have inserted in is real( it exists) , so I dont see any reason this code is not running. I am using windows. Any idea how to fix this? The error is "Exception in thread "main" java.lang.Error: Unresolved compilation problem:

    at ReadData.main(ReadData (1).java:24)"

Edit: import of scanner is not the problem


问:
Angular CLI - How to share prototype functions across the application
I need to have some global prototype functions on the string class. Eg.

```<code>string.prototype.trimWhiteSpaces = function () {
  return this.replace(/ +/g, '');
}
</code>```

I am using Angular CLI and I want this function to be accessible to all strings across my Angular 4 app. I have added the code snippet to a file called prototypes.js and in the .angular-cli.json I loaded the file

```<code>  "scripts": [
      "assets/js/prototypes.js",
      "../node_modules/jquery/dist/jquery.min.js",
      "../node_modules/bootstrap/dist/js/bootstrap.min.js",
      "../node_modules/moment/min/moment.min.js"
    ],
</code>```

However, I keep getting the following error when I compile my project

Property 'trimWhiteSpaces' does not exist on type 'string'.

How do I make such functions accessible throughout my application

答:
You can simply declare such interface as global in a separate file and export it so that typescript knows about it.

So your file e.g. prototypes.ts should look like this:

```<code>export {}; // Using the export, there is no need to import the file anywhere.

declare global {
    interface String {
        trimWhiteSpaces(): string;
    }

    interface Array<T> {
        isEmpty(): boolean;
        isNotEmpty(): boolean;
    }
}

if (!String.prototype.trimWhiteSpaces) {
    String.prototype.trimWhiteSpaces = function(): string {
        return this.replace(/ +/g, '');
    };
}

if (!Array.prototype.isEmpty) {
    Array.prototype.isEmpty = function <T>(): boolean {
        return this?.length === 0;
    };
}

if (!Array.prototype.isNotEmpty) {
    Array.prototype.isNotEmpty = function <T>(): boolean {
        return this?.length > 0;
    };
}
</code>```

Body:
I need to have some global prototype functions on the string class. Eg.

string.prototype.trimWhiteSpaces = function () {
  return this.replace(/ +/g, '');
}

I am using Angular CLI and I want this function to be accessible to all strings across my Angular 4 app. I have added the code snippet to a file called prototypes.js and in the .angular-cli.json I loaded the file

  "scripts": [
      "assets/js/prototypes.js",
      "../node_modules/jquery/dist/jquery.min.js",
      "../node_modules/bootstrap/dist/js/bootstrap.min.js",
      "../node_modules/moment/min/moment.min.js"
    ],

However, I keep getting the following error when I compile my project

Property 'trimWhiteSpaces' does not exist on type 'string'.

How do I make such functions accessible throughout my application

Body:
You can simply declare such interface as global in a separate file and export it so that typescript knows about it.

So your file e.g. prototypes.ts should look like this:

export {}; // Using the export, there is no need to import the file anywhere.

declare global {
    interface String {
        trimWhiteSpaces(): string;
    }

    interface Array<T> {
        isEmpty(): boolean;
        isNotEmpty(): boolean;
    }
}

if (!String.prototype.trimWhiteSpaces) {
    String.prototype.trimWhiteSpaces = function(): string {
        return this.replace(/ +/g, '');
    };
}

if (!Array.prototype.isEmpty) {
    Array.prototype.isEmpty = function <T>(): boolean {
        return this?.length === 0;
    };
}

if (!Array.prototype.isNotEmpty) {
    Array.prototype.isNotEmpty = function <T>(): boolean {
        return this?.length > 0;
    };
}


问:
WooCommerce does not send Order Confirmation email to customer anymore
I am facing a really strange issue in my WooCommerce shop. For a couple of days the "customer_processing_order" email is not sent to the customer anymore. Even when I trigger manually sending this email inside the order details, nothing happens.

In general email, sending works with SMTP data. When I set the status to "Completed" the email is sent. It is only the order confirmation which is not working.

The email is activated and I also checked error logs. I also installed the Preview Plugin for order emails. When I want to generate the preview, I am getting an error:

CRITICAL Uncaught Error: Call to a member function get_billing_first_name() on null in /usr/www/users/diabroq/diabrothers/wp-content/themes/flatsome-child/woocommerce/emails/customer-completed-order.php:28

I don't know if this is related ... normally it was working.

I also installed WP Email Logs Plugin. No emails are generated, so it is not an email delivery issue. The emails that are working have a successful log entry.

I hope somebody can help me ...

答:
I found the issue. It was related to this plugin: "Email Text Customizer for WooCommerce"
After deactivating it was working again ... oh man!</p>


问:
'@media' doesn't affect my Jumbotron header
Hello I've just started web development a few days ago.
I want my web page's header to be responsive so its width, height, font-size be flexible.

```<code><header class="text-white">
<div class="jumbotron bgimg text-white">
  <h1 class="display-4">
    <i class="fa fas fa-star"></i>
    Hello, World!<i class="fa fas fa-star fa-1x"></i></h1>
  <p class="lead">This is my webpage</p>
  <hr class="my-4">
  <p class="lead">Web page details.</p>
  <a class="btn btn-primary" href="./file.zip" download="" role="button">Download!</a>
</div>
</code>```

So I wrote the code like this so that my letter size will be printed small on a small mobile device. My problem is it stays the same and my background image randomly cropped.
Is it because I set display-4 on h1?

```<code>@media (max-width: 400px) {
  #headerh1 {
    width: 100%;
    height: 10%;
    font-size: 2em;
  }
}
</code>```

Thank you, for always.

答:
Issue is with selector simple Use

```<code>h1{
    width: 100%;
    height: 10%;
    font-size: 2em;
}
</code>```

Or

```<code>h1.display-4{
        width: 100%;
        height: 10%;
        font-size: 2em;
    }
</code>```

or more precisely

```<code>header h1.display-4{
        width: 100%;
        height: 10%;
        font-size: 2em;
    }
</code>```

Read more about CSS Selectors

Body:
Hello I've just started web development a few days ago.
I want my web page's header to be responsive so its width, height, font-size be flexible.

    Hello, World!

This is my webpage

Web page details.

  Download!

So I wrote the code like this so that my letter size will be printed small on a small mobile device. My problem is it stays the same and my background image randomly cropped.
Is it because I set display-4 on h1?

@media (max-width: 400px) {
  #headerh1 {
    width: 100%;
    height: 10%;
    font-size: 2em;
  }
}

Thank you, for always.

Body:
Issue is with selector simple Use

h1{
    width: 100%;
    height: 10%;
    font-size: 2em;
}

Or

h1.display-4{
        width: 100%;
        height: 10%;
        font-size: 2em;
    }

or more precisely

header h1.display-4{
        width: 100%;
        height: 10%;
        font-size: 2em;
    }

Read more about CSS Selectors


问:
How to launch container with user namespace configuration?
In the below docker file, base image(jenkins/jenkins) is providing a user jenkins with UID 1000 and GID 1000, within container.

```<code>FROM jenkins/jenkins

# Install some base packages

# Use non-privileged user provided by base image
USER jenkins # with uid 1000 and GID 1000

# Copy plugins and other stuff
</code>```

On the docker host(EC2 instance), we also have similar UID & GID created,

```<code> $ groupadd -g 1000 jenkins
 $ useradd -u 1000 -g jenkins jenkins
 $ mkdir -p /abc/home_folder_for_jenkins
 $ chown -R jenkins:jenkins /abc/home_folder_for_jenkins
</code>```

to make sure, container can write files to /abc/home_folder_for_jenkins in EC2 instance.

Another aspect that we need to take care in same EC2 instance, is to run containers(other than above container) to run in non-privileged mode.

So, below configuration is performed on docker host(EC2):

```<code>$ echo dockremap:165536:65536 > /etc/subuid
$ echo dockremap:165536:65536 > /etc/subgid
$ echo '{"debug":true, "userns-remap":"default"}' > /etc/docker/daemon.json
</code>```

This dockremap configuration is not allowing jenkins to start and docker container goes in Exited state:

```<code>$ ls -l /abc/home_folder_for_jenkins
total 0
</code>```

After removing docker remap configuration, everything work fine.

Why  dockremap configuration not allow the jenkins container to run as jenkins user?

答: User namespaces offset the UID/GID of the user inside the container, and any files inside the container. There is no mapping from the UID/GID inside the container to the external host UID/GID (that would defeat the purpose). Therefore, you would need the offset the UID/GID of the directory being created, or just use a named volume and let docker handle this for you. I believe that UID/GID on the host would be 166536 (165536 + 1000) (I may have an off by one in there, so try opening the directory permissions if this still fails and see what gets created).</p>

Body:
In the below docker file, base image(jenkins/jenkins) is providing a user jenkins with UID 1000 and GID 1000, within container.

FROM jenkins/jenkins

# Install some base packages

# Use non-privileged user provided by base image
USER jenkins # with uid 1000 and GID 1000

# Copy plugins and other stuff

On the docker host(EC2 instance), we also have similar UID & GID created,

 $ groupadd -g 1000 jenkins
 $ useradd -u 1000 -g jenkins jenkins
 $ mkdir -p /abc/home_folder_for_jenkins
 $ chown -R jenkins:jenkins /abc/home_folder_for_jenkins

to make sure, container can write files to /abc/home_folder_for_jenkins in EC2 instance.

Another aspect that we need to take care in same EC2 instance, is to run containers(other than above container) to run in non-privileged mode.

So, below configuration is performed on docker host(EC2):

$ echo dockremap:165536:65536 > /etc/subuid
$ echo dockremap:165536:65536 > /etc/subgid
$ echo '{"debug":true, "userns-remap":"default"}' > /etc/docker/daemon.json

This dockremap configuration is not allowing jenkins to start and docker container goes in Exited state:

$ ls -l /abc/home_folder_for_jenkins
total 0

After removing docker remap configuration, everything work fine.

Why  dockremap configuration not allow the jenkins container to run as jenkins user?