问:
How to force Flutter to rebuild / redraw all widgets?
Is there a way to force Flutter to redraw all widgets (e.g. after locale change)?</p>

答:
Simply Use:

```<code>Navigator.popAndPushNamed(context,'/screenname');
</code>```

Whenever you need to refresh :)

Body:
Simply Use:

Navigator.popAndPushNamed(context,'/screenname');

Whenever you need to refresh :)


来源: stackexchange

问:
Find each element with attr type without element type
I'd like to find each element with an attr of name and replace part of the string.  The caveat is I don't wish to target them by element type.
The below doesn't work:

```<code>       var index = 0;
       $('.foil').each(function () {
            $(this).each(function () {
                attr = $(this).attr('name');
                if (typeof attr !== typeof undefined && attr !== false){
                    console.log(attr);
                    attr.replace(/\[(.+?)\]/g, '[' + index + ']');
                }
            });
           index++;
       });
</code>```

This was the solution that worked:

```<code>                $(this).find('[name]').each(function () {
                    $(this).attr('name', $(this).attr('name').replace(/\[(.+?)\]/g, '[' + index + ']'));
                });
</code>```

答:
You can use the selector [name] to find any element with the name attribute. You can also combine this with the class selector.

You can give a function to the .attr() method, it will automatically execute it for each matching element, so you don't need .each().

There's no need for nested .each(). You just need to iterate over the elements once.

$(".foil[name]").attr("name", function(i, name) {
    return name.replace(/\[.*\]/, '[' + i + ']');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="foil" type="text" name="txtfield[23]" />
<input class="foil" type="text" name="txtfield[60]" />
<input class="foil" type="text"></code>```

If you inspect the input elements, you'll see that they're changed to:

```<code>    <input class="foil" type="text" name="txtfield[0]" />
    <input class="foil" type="text" name="txtfield[1]" />
    <input class="foil" type="text">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to find each element with an attr of name and replace part of the string.  The caveat is I don't wish to target them by element type.
The below doesn't work:

       var index = 0;
       $('.foil').each(function () {
            $(this).each(function () {
                attr = $(this).attr('name');
                if (typeof attr !== typeof undefined && attr !== false){
                    console.log(attr);
                    attr.replace(/\[(.+?)\]/g, '[' + index + ']');
                }
            });
           index++;
       });

This was the solution that worked:

                $(this).find('[name]').each(function () {
                    $(this).attr('name', $(this).attr('name').replace(/\[(.+?)\]/g, '[' + index + ']'));
                });

Body:
You can use the selector [name] to find any element with the name attribute. You can also combine this with the class selector.

You can give a function to the .attr() method, it will automatically execute it for each matching element, so you don't need .each().

There's no need for nested .each(). You just need to iterate over the elements once.

$(".foil[name]").attr("name", function(i, name) {
    return name.replace(/\[.*\]/, '[' + i + ']');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="foil" type="text" name="txtfield[23]" />
<input class="foil" type="text" name="txtfield[60]" />
<input class="foil" type="text">

If you inspect the input elements, you'll see that they're changed to:

    <input class="foil" type="text" name="txtfield[0]" />
    <input class="foil" type="text" name="txtfield[1]" />
    <input class="foil" type="text">


问:
Is it acceptable to `const_cast<Foo*>(this)` if public state doesn't change?
I have a C++ class that calculates some statistic parameters on the go. Is it acceptable to cast away const from this to implement caching of lengthy computations, if I don't change publicly visible state, and const function in question is idempotent and pure/referentially transparent?

```<code>#include <cstdio>
#include <unistd.h>

class Compute {
public:
    Compute() = default;
    ~Compute() = default;

    void add(int x) {
        sum += x;
        squareDirty = true;
    }

    int getSquare() const {
        if (squareDirty) {
            auto &mthis = *const_cast<Compute*>(this);
            usleep(2000); // takes a long time!
            mthis.squareCached = sum * sum;
            mthis.squareDirty = false;
        }

        return squareCached;
    }

private:
    int sum = 0;
    bool squareDirty = false;
    int squareCached;
};

void foo() {
    Compute c{};
    c.add(10);
    c.add(20);
    printf("%d\n", c.getSquare()); // long time...
    printf("%d\n", c.getSquare()); // fast!
}
</code>```

I want to lazily compute things only when they are actually needed — and cache them until new data arrives.

However, caching things means that my T getSquare() const method would have to cast away const from this to mutate private state.

But as getSquare is effectively idempotent, compiler can compute it once and store as constant, or inline, or do whatever else, as my private state is discardable.

Is this an acceptable thing to do, or am I asking for UB?

答:
This problem is solved by using the mutable keyword. This keyword indicates that the member variable can be modified in a const qualified function:

```<code>struct S
{
  mutable int x;  // some data that is not relevant to users of the object (e.g. a cache variable)
  int y;

  void f() const
  {
     x = 42;  // fine
     y = 42;  // error
  }
};
</code>```

This is a much better way to modify variables in a const qualified function, than either giving up const-correctness, or using const_cast (which is a potential source of UB).

Note that when you make a function const, you actually guarantee something more than "the visible state is not changed". You are guaranteeing that accesses to an object via any const functions are thread-safe. This means that if you have mutable variables, you should think carefully about their state, if multiple threads might access them simultaneously. You should probably consider manually synchronizing accesses to this variable yourself in that case.

Body:
I have a C++ class that calculates some statistic parameters on the go. Is it acceptable to cast away const from this to implement caching of lengthy computations, if I don't change publicly visible state, and const function in question is idempotent and pure/referentially transparent?

#include <cstdio>
#include <unistd.h>

class Compute {
public:
    Compute() = default;
    ~Compute() = default;

    void add(int x) {
        sum += x;
        squareDirty = true;
    }

    int getSquare() const {
        if (squareDirty) {
            auto &mthis = *const_cast<Compute*>(this);
            usleep(2000); // takes a long time!
            mthis.squareCached = sum * sum;
            mthis.squareDirty = false;
        }

        return squareCached;
    }

private:
    int sum = 0;
    bool squareDirty = false;
    int squareCached;
};

void foo() {
    Compute c{};
    c.add(10);
    c.add(20);
    printf("%d\n", c.getSquare()); // long time...
    printf("%d\n", c.getSquare()); // fast!
}

I want to lazily compute things only when they are actually needed — and cache them until new data arrives.

However, caching things means that my T getSquare() const method would have to cast away const from this to mutate private state.

But as getSquare is effectively idempotent, compiler can compute it once and store as constant, or inline, or do whatever else, as my private state is discardable.

Is this an acceptable thing to do, or am I asking for UB?

Body:
This problem is solved by using the mutable keyword. This keyword indicates that the member variable can be modified in a const qualified function:

struct S
{
  mutable int x;  // some data that is not relevant to users of the object (e.g. a cache variable)
  int y;

  void f() const
  {
     x = 42;  // fine
     y = 42;  // error
  }
};

This is a much better way to modify variables in a const qualified function, than either giving up const-correctness, or using const_cast (which is a potential source of UB).

Note that when you make a function const, you actually guarantee something more than "the visible state is not changed". You are guaranteeing that accesses to an object via any const functions are thread-safe. This means that if you have mutable variables, you should think carefully about their state, if multiple threads might access them simultaneously. You should probably consider manually synchronizing accesses to this variable yourself in that case.


问:
How do I monitor clipboard changes in C#?
Is there a clipboard changed or updated event that i can access through C#?</p>

答:
I think you'll have to use some p/invoke:

```<code>[DllImport("User32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);
</code>```

See this article on how to set up a clipboard monitor in c#

Basically you register your app as a clipboard viewer using

```<code>_ClipboardViewerNext = SetClipboardViewer(this.Handle);
</code>```

and then you will recieve the WM_DRAWCLIPBOARD message, which you can handle by overriding WndProc:

```<code>protected override void WndProc(ref Message m)
{
    switch ((Win32.Msgs)m.Msg)
    {
        case Win32.Msgs.WM_DRAWCLIPBOARD:
        // Handle clipboard changed
        break;
        // ...
   }
}
</code>```

(There's more to be done; passing things along the clipboard chain and unregistering your view, but you can get that from the article)

OwnerDisplayName: Sevki

LastEditorDisplayName: Nick

Body:
I think you'll have to use some p/invoke:

[DllImport("User32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);

See this article on how to set up a clipboard monitor in c#

Basically you register your app as a clipboard viewer using

_ClipboardViewerNext = SetClipboardViewer(this.Handle);

and then you will recieve the WM_DRAWCLIPBOARD message, which you can handle by overriding WndProc:

protected override void WndProc(ref Message m)
{
    switch ((Win32.Msgs)m.Msg)
    {
        case Win32.Msgs.WM_DRAWCLIPBOARD:
        // Handle clipboard changed
        break;
        // ...
   }
}

(There's more to be done; passing things along the clipboard chain and unregistering your view, but you can get that from the article)

OwnerDisplayName: Daniel L

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Daniel L


问:
Do unused functions get optimized out?
Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?</p>

答: Quite a lot of the time, yes.  It’s often called linker stripping.</p>

Title: Do unused functions get optimized out?


问:
Getting the average number of times a number appears between other numbers
In my cells I have three possible different values, 1 ,0 or ND. I want to get the average number of times 0 appears between the 1s.
But I cannot seem to get it, I have been playing around with =AVERAGE(COUNTIF(A60:C60,  0)). It seems simple but I cannot figure it out.
So I want the average number of times that 0 appears between 1s in the whole row.

imagine each cell is a day. 1s represent fail and 0 represent pass. If the cell has failed that day it is fixed that night. what i want to find out is when i fix a failed cell what is the average amount of days pass before that cell fails again

答:
Sorry, my reputation is too low to make comments.
I agree with the solution of M.S. with small corrections.

Making the life a bit easier I would ignore the starting 0, so I deleted them. Anyway they are not between ones.

The number of 1s shall be reduced with 1, while there are one less intervals between the ones.

After it the ration shall give the average:

```<code>=COUNTIF(A60:C60,0)/(COUNTIF(A60:C60,1)-1)
</code>```

Body:
Sorry, my reputation is too low to make comments.
I agree with the solution of M.S. with small corrections.

Making the life a bit easier I would ignore the starting 0, so I deleted them. Anyway they are not between ones.

The number of 1s shall be reduced with 1, while there are one less intervals between the ones.

After it the ration shall give the average:

=COUNTIF(A60:C60,0)/(COUNTIF(A60:C60,1)-1)


答:
Is it acceptable to const_cast<Foo*>(this) if public state doesn't change?

It is undefined behaviour to modify non-mutable state of a const object.

For that reason, it is not acceptable to modify non-mutable state through a reference to const after const cast unless it is provable that the referred object is non-const.

Whether that state is public is irrelevant. This type of transparent caching is the reason why mutable members exist, I think.

Title: Is it acceptable to `const_cast<Foo*>(this)` if public state doesn't change?


问:
How to make a function in Vanilla JS that puts checked attribute to the radio inputs before the selected input?
I can't find solution for this one.

Need to put attribute checked on the inputs that are before the selected input with JavaScript and the inputs after it unchecked.

UPD: changed the input type to the "checkbox" and now I need a function that marks "checked" the checkboxes before the last checked one, while unchecking succeeding boxes in case they were checked before.

Note: The solution has to use ES5 compatible syntax.

With code examples, please !

<input type="checkbox" id="product-1" name="toggle">
<input type="checkbox" id="product-2" name="toggle">
<input type="checkbox" id="product-3" name="toggle">
<input type="checkbox" id="product-4" name="toggle">
<input type="checkbox" id="product-5" name="toggle">
```

答:
The default behavior of <input type="radio"> is to allow only one of the inputs / options to be selected. Because of this, only the last input is being marked with your JS code.
To be able to select multiple options, use <input type="checkbox">.
For more reference: MDN Docs.


问:
Windows service works when running through command line but not through Services
Following this guide I created a service from a python script and used "py [script name] install". The service was installed successfully and I can see it in the services window. If I run the service through the command line using "py [script name] start", it all works correctly.

However, when I try to start it from the Windows Services window, it gives a different error depending on the account I use. All of these are suggestions I've seen on various forums:

1) Default (Local System Account)

When I try this one, it gives error "Windows could not start the service on Local Computer."

2) The admin account, which I'm running the cmd from

Same error as above

3) LOCAL SERVICE

Gives "Error 5: Access is denied." even though I'm logged in as admin.

Does anyone know what could be causing this?

I also tried creating a .exe from the python script and adding that as a service using sc.exe. However, when I did that, I never got past "The service did not respond to the start or control request in a timely fashion." This error also occurred when running it from the CMD until I copied some files into a directory in the python installation.

答:
I've never tried a python script as a service, so I can't speak to that directly.

I do know that the "The service did not respond to the start or control request in a timely fashion." error is almost always an indication that the OnStart() callback to the service (looks like SvcDoRun in your case) starts a long running operation (e.g., while loop) that never returns.  The OnStart() callback is expected to kick off a foreground thread that will keep the service running and then return.  From my recollection, if OnStart() doesn't return in about 30 seconds or so, Windows kills the service as unresponsive, which trigger this particular error message.

Another thing to look at is the event viewer.  It may be that your service is throwing an exception that you're not seeing due to process isolation.


问:
How do I use arrow functions in React
I'm working on a node and react project where when i try to use an arrow function, it brings the error that the function is not defined. I've tried following every tutorial I can get but I'm not able to solve this. Here is my code;

```<code>import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

  Trial = ()=>{
    return(
      <div>this is my div</div>
    );
  }

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <Trial />

    </div>
  );
}
}

export default App;
</code>```

and the error message i'm getting is:

```<code>./src/App.js
  Line 33:8:  'Trial' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed
</code>```

any assistance will be highly appreciated

答:
As I have gone through your code you can access your arrow function by calling it correctly you just have to change below code.

```<code>render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <this.Trial />

    </div>
  );
}
</code>```

or better way to access this

```<code>render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      {this.trial()}

    </div>
  );
}
</code>```

Title: How do I use arrow functions in React

Body:
I'm working on a node and react project where when i try to use an arrow function, it brings the error that the function is not defined. I've tried following every tutorial I can get but I'm not able to solve this. Here is my code;

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

  Trial = ()=>{
    return(

this is my div

    );
  }

render(){
  return (

{this.state.apiResponse}

      <Trial />

  );
}
}

export default App;

and the error message i'm getting is:

./src/App.js
  Line 33:8:  'Trial' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed

any assistance will be highly appreciated

Body:
As I have gone through your code you can access your arrow function by calling it correctly you just have to change below code.

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <this.Trial />

    </div>
  );
}

or better way to access this

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      {this.trial()}

    </div>
  );
}


问:
MySQL update with subselect too slow
Having an issue with an update query taking more than 20 minutes (I kill it after that).

Scenario:

Table one has some 300K records.

Table two contains the same set of records (copied over), but with an extra field that needs to contain the id of the record that matches a number of fields, and has the highest value of another (a score). To clarify, the end result should be table two containing 300K records with each record having the id of another record that has the same set of basic properties, and the highest score within the set of records with those properties.

The below completes in ~5s when I only copy 2K records instead of the full 300k records into table two.

UPDATE vtable2 v1 SET v1.buddy = (
    SELECT v2.id FROM vtable1 v2
    WHERE
    v2.group_id = v1.group_id AND
    // 6 more basic comparisons
    ORDER BY score DESC LIMIT 1
)
```

I need to find buddies for the full 300K records. All fields involved in joining and sorting have indexes.

Help much appreciated.

答:
you could test with numeric variable

```<code> SELECT v2.id FROM vtable1 v2
WHERE
v2.group_id = 1 AND
// 6 more basic comparisons
ORDER BY score DESC LIMIT 1
</code>```

Anyway I think use Join it's better but I don't have schema DB.

Maybe you have a trouble about index on your sql DB.

Title: MySQL update with subselect too slow

Body:
Having an issue with an update query taking more than 20 minutes (I kill it after that).

Scenario:

Table one has some 300K records.

Table two contains the same set of records (copied over), but with an extra field that needs to contain the id of the record that matches a number of fields, and has the highest value of another (a score). To clarify, the end result should be table two containing 300K records with each record having the id of another record that has the same set of basic properties, and the highest score within the set of records with those properties.

The below completes in ~5s when I only copy 2K records instead of the full 300k records into table two.

UPDATE vtable2 v1 SET v1.buddy = (
    SELECT v2.id FROM vtable1 v2
    WHERE
    v2.group_id = v1.group_id AND
    // 6 more basic comparisons
    ORDER BY score DESC LIMIT 1
)

I need to find buddies for the full 300K records. All fields involved in joining and sorting have indexes.

Help much appreciated.

Body:
you could test with numeric variable

 SELECT v2.id FROM vtable1 v2
WHERE
v2.group_id = 1 AND
// 6 more basic comparisons
ORDER BY score DESC LIMIT 1

Anyway I think use Join it's better but I don't have schema DB.

Maybe you have a trouble about index on your sql DB.


问:
The z-index of SwiftUI View and UIKit View
The SwiftUI scroll view is hiding some area of a view presented from UIViewControllerRepresentable viewController.

Part of the SwiftUI code, The GoogleMapsView is the UIViewControllerRepresentable viewController.

```<code>struct ContentView: View {

var body: some View {
    ZStack(alignment: .top) {

        GoogleMapsView()

        VStack(alignment: .leading) {
            Text("Top Locations near you")

            ScrollView(.horizontal, showsIndicators: false) {
                HStack() {
                    ForEach(dataSource.topPlaces) { place in
                        PlaceCardView(placeImage: place.image, placeName: place.name, placeRating: place.rating, placeRatingTotal: place.ratingTotal, topPlace: place)
                    }
                }
                .padding(.horizontal, 10)
            }
            .background(Color.clear)
            .foregroundColor(.black)
            .frame(height: 200)
            .opacity(self.finishedFetching ? 1 : 0.1)
            .animation(.easeInOut(duration: 1.3))
    }.edgesIgnoringSafeArea(.all)
}
</code>```

The view I want to put on the top is from the GoogleMapView() which I put it on the "bottom" of the ZStack because I want that Scroll view to flow on the map. However the view show on the map when marker is tapped is cover up by the SwiftUI ScrollView

I tried to change their zIndex of the scrollView, zPosition of the pop up view or bringSubviewToFront etc. None of them work.

答:
You need to inject local state via binding into `` and change it there on popup shown/hidden.

Here is some pseudo code

```<code>struct ContentView: View {

@State private var isPopup = false

var body: some View {
    ZStack(alignment: .top) {

        GoogleMapsView(isPopup: $isPopup)

        VStack(alignment: .leading) {
            Text("Top Locations near you")

            if !isPopup {
               ScrollView(.horizontal, showsIndicators: false) {
                  // other code
               }
               // other code
            }
    }.edgesIgnoringSafeArea(.all)
}

struct GoogleMapsView : UIViewControllerRepresentable {
   @Binding isPopup: Bool

   // other code

   // make self.isPopup = true before popup and false after
</code>```

Body:
The SwiftUI scroll view is hiding some area of a view presented from UIViewControllerRepresentable viewController.

Part of the SwiftUI code, The GoogleMapsView is the UIViewControllerRepresentable viewController.

struct ContentView: View {

var body: some View {
    ZStack(alignment: .top) {

        GoogleMapsView()

        VStack(alignment: .leading) {
            Text("Top Locations near you")

            ScrollView(.horizontal, showsIndicators: false) {
                HStack() {
                    ForEach(dataSource.topPlaces) { place in
                        PlaceCardView(placeImage: place.image, placeName: place.name, placeRating: place.rating, placeRatingTotal: place.ratingTotal, topPlace: place)
                    }
                }
                .padding(.horizontal, 10)
            }
            .background(Color.clear)
            .foregroundColor(.black)
            .frame(height: 200)
            .opacity(self.finishedFetching ? 1 : 0.1)
            .animation(.easeInOut(duration: 1.3))
    }.edgesIgnoringSafeArea(.all)
}

The view I want to put on the top is from the GoogleMapView() which I put it on the "bottom" of the ZStack because I want that Scroll view to flow on the map. However the view show on the map when marker is tapped is cover up by the SwiftUI ScrollView

I tried to change their zIndex of the scrollView, zPosition of the pop up view or bringSubviewToFront etc. None of them work.

Body:
You need to inject local state via binding into `` and change it there on popup shown/hidden.

Here is some pseudo code

struct ContentView: View {

@State private var isPopup = false

var body: some View {
    ZStack(alignment: .top) {

        GoogleMapsView(isPopup: $isPopup)

        VStack(alignment: .leading) {
            Text("Top Locations near you")

            if !isPopup {
               ScrollView(.horizontal, showsIndicators: false) {
                  // other code
               }
               // other code
            }
    }.edgesIgnoringSafeArea(.all)
}

struct GoogleMapsView : UIViewControllerRepresentable {
   @Binding isPopup: Bool

   // other code

   // make self.isPopup = true before popup and false after


问:
AttributeError: 'Model' object has no attribute 'trainable_variables' when model is <class 'keras.engine.training.Model'>
I've just started to learn Tensorflow (2.1.0), Keras (2.3.1) and Python 3.7.7.

By the way, I'm running all my code on an Anaconda Environment on Windows 7 64bit. I have also tried on an Anaconda Environment on Linux and I get the same error.

I'm following this Tensorflow's tutorial: "Custom training: walkthrough".

Everything is ok, but when I typed this piece of code:

```<code>def grad(model, inputs, targets):
  with tf.GradientTape() as tape:
    loss_value = loss(model, inputs, targets, training=True)
  return loss_value, tape.gradient(loss_value, model.trainable_variables)
</code>```

I get the error:

Instance of 'Model' has no 'trainable_variables' member

This is my model, with all of its imports:

```<code>import keras
from keras.models import Input, Model
from keras.layers import Dense, Conv2D, Conv2DTranspose, UpSampling2D, MaxPooling2D, Flatten, ZeroPadding2D
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
import numpy as np
import tensorflow as tf

def vgg16_encoder_decoder(input_size = (200,200,1)):
    #################################
    # Encoder
    #################################
    inputs = Input(input_size, name = 'input')

    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_1')(inputs)
    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_2')(conv1)
    pool1 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_1')(conv1)

    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_1')(pool1)
    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_2')(conv2)
    pool2 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_2')(conv2)

    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_1')(pool2)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_2')(conv3)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_3')(conv3)
    pool3 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_3')(conv3)

    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_1')(pool3)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_2')(conv4)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_3')(conv4)
    pool4 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_4')(conv4)

    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_1')(pool4)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_2')(conv5)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_3')(conv5)
    pool5 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_5')(conv5)

    #################################
    # Decoder
    #################################
    #conv1 = Conv2DTranspose(512, (2, 2), strides = 2, name = 'conv1')(pool5)

    upsp1 = UpSampling2D(size = (2,2), name = 'upsp1')(pool5)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_1')(upsp1)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_2')(conv6)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_3')(conv6)

    upsp2 = UpSampling2D(size = (2,2), name = 'upsp2')(conv6)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_1')(upsp2)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_2')(conv7)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_3')(conv7)
    zero1 = ZeroPadding2D(padding =  ((1, 0), (1, 0)), data_format = 'channels_last', name='zero1')(conv7)

    upsp3 = UpSampling2D(size = (2,2), name = 'upsp3')(zero1)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_1')(upsp3)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_2')(conv8)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_3')(conv8)

    upsp4 = UpSampling2D(size = (2,2), name = 'upsp4')(conv8)
    conv9 = Conv2D(128, 3, activation = 'relu', padding = 'same', name = 'conv9_1')(upsp4)
    conv9 = Conv2D(128, 3, activation = 'relu', padding = 'same', name = 'conv9_2')(conv9)

    upsp5 = UpSampling2D(size = (2,2), name = 'upsp5')(conv9)
    conv10 = Conv2D(64, 3, activation = 'relu', padding = 'same', name = 'conv10_1')(upsp5)
    conv10 = Conv2D(64, 3, activation = 'relu', padding = 'same', name = 'conv10_2')(conv10)

    conv11 = Conv2D(1, 3, activation = 'relu', padding = 'same', name = 'conv11')(conv10)

    model = Model(inputs = inputs, outputs = conv11, name = 'vgg-16_encoder_decoder')

    return model
</code>```

I have found any reference for that attribute in Tensorflow Keras Model documentation.

On "Migrate your TensorFlow 1 code to TensorFlow 2 - 2. Make the code 2.0-native", say:

If you need to aggregate lists of variables (like
  tf.Graph.get_collection(tf.GraphKeys.VARIABLES)), use the .variables
  and .trainable_variables attributes of the Layer and Model objects.

The network in Tensorflow's tutorial "Custom training: walkthrough" is:

```<code>model = tf.keras.Sequential([
  tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(4,)),  # input shape required
  tf.keras.layers.Dense(10, activation=tf.nn.relu),
  tf.keras.layers.Dense(3)
])
</code>```

When I do:

```<code>print(type(model))
</code>```

I get:

```<code><class 'tensorflow.python.keras.engine.sequential.Sequential'>
</code>```

But if I print the type of my network, vgg16_encoder_decoder, I get:

```<code><class 'keras.engine.training.Model'>
</code>```

So, the problem is the type of the network. I haven't say the above class, 'keras.engine.training.Model', before.

How can I fix this problem to let me use the attribute trainable_variables?

答:
The problem is that you are using keras library instead of tensorflow.keras.
When using tensorflow it is highly recommended to use its own keras implementation.

This code should works

```<code>import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Conv2D, Conv2DTranspose, UpSampling2D, MaxPooling2D, Flatten, ZeroPadding2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
import numpy as np

def vgg16_encoder_decoder(input_size = (200,200,1)):
    # Your code here (no change needed)

model = vgg16_encoder_decoder()
model.trainable_variables
</code>```

Body:
I've just started to learn Tensorflow (2.1.0), Keras (2.3.1) and Python 3.7.7.

By the way, I'm running all my code on an Anaconda Environment on Windows 7 64bit. I have also tried on an Anaconda Environment on Linux and I get the same error.

I'm following this Tensorflow's tutorial: "Custom training: walkthrough".

Everything is ok, but when I typed this piece of code:

def grad(model, inputs, targets):
  with tf.GradientTape() as tape:
    loss_value = loss(model, inputs, targets, training=True)
  return loss_value, tape.gradient(loss_value, model.trainable_variables)

I get the error:

Instance of 'Model' has no 'trainable_variables' member

This is my model, with all of its imports:

import keras
from keras.models import Input, Model
from keras.layers import Dense, Conv2D, Conv2DTranspose, UpSampling2D, MaxPooling2D, Flatten, ZeroPadding2D
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
import numpy as np
import tensorflow as tf

def vgg16_encoder_decoder(input_size = (200,200,1)):
    #################################
    # Encoder
    #################################
    inputs = Input(input_size, name = 'input')

    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_1')(inputs)
    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_2')(conv1)
    pool1 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_1')(conv1)

    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_1')(pool1)
    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_2')(conv2)
    pool2 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_2')(conv2)

    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_1')(pool2)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_2')(conv3)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_3')(conv3)
    pool3 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_3')(conv3)

    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_1')(pool3)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_2')(conv4)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_3')(conv4)
    pool4 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_4')(conv4)

    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_1')(pool4)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_2')(conv5)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_3')(conv5)
    pool5 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_5')(conv5)

    #################################
    # Decoder
    #################################
    #conv1 = Conv2DTranspose(512, (2, 2), strides = 2, name = 'conv1')(pool5)

    upsp1 = UpSampling2D(size = (2,2), name = 'upsp1')(pool5)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_1')(upsp1)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_2')(conv6)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_3')(conv6)

    upsp2 = UpSampling2D(size = (2,2), name = 'upsp2')(conv6)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_1')(upsp2)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_2')(conv7)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_3')(conv7)
    zero1 = ZeroPadding2D(padding =  ((1, 0), (1, 0)), data_format = 'channels_last', name='zero1')(conv7)

    upsp3 = UpSampling2D(size = (2,2), name = 'upsp3')(zero1)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_1')(upsp3)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_2')(conv8)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_3')(conv8)

    upsp4 = UpSampling2D(size = (2,2), name = 'upsp4')(conv8)
    conv9 = Conv2D(128, 3, activation = 'relu', padding = 'same', name = 'conv9_1')(upsp4)
    conv9 = Conv2D(128, 3, activation = 'relu', padding = 'same', name = 'conv9_2')(conv9)

    upsp5 = UpSampling2D(size = (2,2), name = 'upsp5')(conv9)
    conv10 = Conv2D(64, 3, activation = 'relu', padding = 'same', name = 'conv10_1')(upsp5)
    conv10 = Conv2D(64, 3, activation = 'relu', padding = 'same', name = 'conv10_2')(conv10)

    conv11 = Conv2D(1, 3, activation = 'relu', padding = 'same', name = 'conv11')(conv10)

    model = Model(inputs = inputs, outputs = conv11, name = 'vgg-16_encoder_decoder')

    return model

I have found any reference for that attribute in Tensorflow Keras Model documentation.

On "Migrate your TensorFlow 1 code to TensorFlow 2 - 2. Make the code 2.0-native", say:

If you need to aggregate lists of variables (like
  tf.Graph.get_collection(tf.GraphKeys.VARIABLES)), use the .variables
  and .trainable_variables attributes of the Layer and Model objects.

The network in Tensorflow's tutorial "Custom training: walkthrough" is:

model = tf.keras.Sequential([
  tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(4,)),  # input shape required
  tf.keras.layers.Dense(10, activation=tf.nn.relu),
  tf.keras.layers.Dense(3)
])

When I do:

print(type(model))

I get:

<class 'tensorflow.python.keras.engine.sequential.Sequential'>

But if I print the type of my network, vgg16_encoder_decoder, I get:

<class 'keras.engine.training.Model'>

So, the problem is the type of the network. I haven't say the above class, 'keras.engine.training.Model', before.

How can I fix this problem to let me use the attribute trainable_variables?

Body:
The problem is that you are using keras library instead of tensorflow.keras.
When using tensorflow it is highly recommended to use its own keras implementation.

This code should works

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Conv2D, Conv2DTranspose, UpSampling2D, MaxPooling2D, Flatten, ZeroPadding2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
import numpy as np

def vgg16_encoder_decoder(input_size = (200,200,1)):
    # Your code here (no change needed)

model = vgg16_encoder_decoder()
model.trainable_variables


答:
Using

```<code>auto &mthis = *const_cast<Compute*>(this);
mthis.squareCached = sum * sum;
mthis.squareDirty = false;
</code>```

can cause undefined behavior. It depends on how the original object was constructed.

From https://en.cppreference.com/w/cpp/language/const_cast:

Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior.

It will be better to make the relevant members mutable.

```<code>int sum = 0;
mutable bool squareDirty = false;
mutable int squareCached;
</code>```

Then, you may use:

```<code>int getSquare() const {
    if (squareDirty) {
        usleep(2000); // takes a long time!
        this->squareCached = sum * sum;
        this->squareDirty = false;
    }

    return squareCached;
}
</code>```

without fear of undefined behavior.

Body:
Using

auto &mthis = *const_cast<Compute*>(this);
mthis.squareCached = sum * sum;
mthis.squareDirty = false;

can cause undefined behavior. It depends on how the original object was constructed.

From https://en.cppreference.com/w/cpp/language/const_cast:

Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior.

It will be better to make the relevant members mutable.

int sum = 0;
mutable bool squareDirty = false;
mutable int squareCached;

Then, you may use:

int getSquare() const {
    if (squareDirty) {
        usleep(2000); // takes a long time!
        this->squareCached = sum * sum;
        this->squareDirty = false;
    }

    return squareCached;
}

without fear of undefined behavior.


问:
How to filter data by column content?
I imported CSV file with data about airports. Countries are in column "Country Name". I want to work only with data about Ukrainian, German and Polish airports. I filtered my data, but I only know how to pick one country. How I can filter my data for two or more desired countries? I'm using python 3.8.1.

My code:

```<code>filtered_data = df[df["Country Name"]=="Poland"]
print(filtered_data)
</code>```

答:
I guess you need this

filtered_data = df[(df["Country Name"]=="Poland") | (df["Country Name"]=="Germany") | (df["Country Name"]=="Ukraine")]
print(filtered_data)
```

To specify multiple conditions, you need to combine the various conditions using boolean operators **(NOTE: & instead of and, | instead of or, so on)

Title: How to filter data by column content?

Body:
I imported CSV file with data about airports. Countries are in column "Country Name". I want to work only with data about Ukrainian, German and Polish airports. I filtered my data, but I only know how to pick one country. How I can filter my data for two or more desired countries? I'm using python 3.8.1.

My code:

filtered_data = df[df["Country Name"]=="Poland"]
print(filtered_data)

Body:
I guess you need this

filtered_data = df[(df["Country Name"]=="Poland") | (df["Country Name"]=="Germany") | (df["Country Name"]=="Ukraine")]
print(filtered_data)

To specify multiple conditions, you need to combine the various conditions using boolean operators **(NOTE: & instead of and, | instead of or, so on)


问:
How to dynamically change color of row in a table when it is load
I am using Angular 1.6.
I have a table:

    QTY
    PRICE
    TIME

    1
    20.00
    08:08

    2
    30.00
    08:08

```

I needed when the table is loaded, changed the row background color dynamically when current time minus traded time is less than 5 seconds to yellow.

After 5 seconds, the background is changed back to white.

Any help or hint would be greatly appreciated it!

答:
You can use ng-style directive here
The ng-style directive allows you to set CSS style on an HTML element conditionally.

And you can use it in your table as follows

Let's say you have trade transaction time in "transaction_time" and the current time in "current_time".

```<code><table>
  <tr>
    <th>QTY</th>
    <th>PRICE</th>
    <th>TIME</th>
  </tr>
  <tr ng-repeat="trade in stockMarket track by $index" ng-style="trade.transaction_time - current_time <=5 && { 'background-color': 'yellow' } || trade.transaction_time-current_time>10 && { 'background-color': 'white'}" >
    <td>{{$index}}</td>
    <td>{{trade.amount}}</td>
    <td>{{trade.transaction_time}}</td>
  </tr>
</table>

</code>```

I hope this helps you.

Body:
I am using Angular 1.6.
I have a table:

    QTY
    PRICE
    TIME

    1
    20.00
    08:08

    2
    30.00
    08:08

I needed when the table is loaded, changed the row background color dynamically when current time minus traded time is less than 5 seconds to yellow.

After 5 seconds, the background is changed back to white.

Any help or hint would be greatly appreciated it!

Body:
You can use ng-style directive here
The ng-style directive allows you to set CSS style on an HTML element conditionally.

And you can use it in your table as follows

Let's say you have trade transaction time in "transaction_time" and the current time in "current_time".

<table>
  <tr>
    <th>QTY</th>
    <th>PRICE</th>
    <th>TIME</th>
  </tr>
  <tr ng-repeat="trade in stockMarket track by $index" ng-style="trade.transaction_time - current_time <=5 && { 'background-color': 'yellow' } || trade.transaction_time-current_time>10 && { 'background-color': 'white'}" >
    <td>{{$index}}</td>
    <td>{{trade.amount}}</td>
    <td>{{trade.transaction_time}}</td>
  </tr>
</table>

I hope this helps you.


问:
Program with threads for matrix multiplication
I'm trying to create a Java program with threads for matrix multiplication. This is the source code:

```<code>import java.util.Random;

public class MatrixTest {
    //Creating the matrix
    static int[][] mat = new int[3][3];
    static int[][] mat2 = new int[3][3];
    static int[][] result = new int[3][3];

    public static void main(String[] args) {
        //Creating the object of random class
        Random rand = new Random();

        //Filling first matrix with random values
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                mat[i][j] = rand.nextInt(10);
            }
        }

        //Filling second matrix with random values
        for (int i = 0; i < mat2.length; i++) {
            for (int j = 0; j < mat2[i].length; j++) {
                mat2[i][j] = rand.nextInt(10);
            }
        }

        try {
            //Object of multiply Class
            Multiply multiply = new Multiply(3, 3);

            //Threads
            MatrixMultiplier thread1 = new MatrixMultiplier(multiply);
            MatrixMultiplier thread2 = new MatrixMultiplier(multiply);
            MatrixMultiplier thread3 = new MatrixMultiplier(multiply);

            //Implementing threads
            Thread th1 = new Thread(thread1);
            Thread th2 = new Thread(thread2);
            Thread th3 = new Thread(thread3);

            //Starting threads
            th1.start();
            th2.start();
            th3.start();

            th1.join();
            th2.join();
            th3.join();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Printing the result
        System.out.println("\n\nResult:");
        for (int i = 0; i < result.length; i++) {
            for (int j = 0; j < result[i].length; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
    }//End main
}//End Class

//Multiply Class
class Multiply extends MatrixTest {
    private int i;
    private int j;
    private int chance;

    public Multiply(int i, int j) {
        this.i = i;
        this.j = j;
        chance = 0;
    }

    //Matrix Multiplication Function
    public synchronized void multiplyMatrix() {
        int sum = 0;
        int a = 0;
        for (a = 0; a < i; a++) {
            sum = 0;
            for (int b = 0; b < j; b++) {
                sum = sum + mat[chance][b] * mat2[b][a];
            }
            result[chance][a] = sum;
        }

        if (chance >= i)
            return;
        chance++;
    }
}//End multiply class

//Thread Class
class MatrixMultiplier implements Runnable {
    private final Multiply mul;

    public MatrixMultiplier(Multiply mul) {
        this.mul = mul;
    }

    @Override
    public void run() {
        mul.multiplyMatrix();
    }
}
</code>```

I just tried on Eclipse and it works, but now I want to create another version of that program in which, I use one thread for each cell that I'll have on the result matrix. For example I've got two 3x3 matrices. So the result matrix will be 3x3. Then, I want to use 9 threads to calculate each one of the 9 cells of the result matrix.

Can anyone help me?

答:
Consider Matrix.java and Main.java as follows.

public class Matrix extends Thread {
    private static int[][] a;
    private static int[][] b;
    private static int[][] c;

    /* You might need other variables as well */
    private int i;
    private int j;
    private int z1;

    private int s;
    private int k;

    public Matrix(int[][] A, final int[][] B, final int[][] C, int i, int j, int z1) { // need to change this, might
        // need some information
        a = A;
        b = B;
        c = C;
        this.i = i;
        this.j = j;
        this.z1 = z1; // a[0].length
    }

    public void run() {
        synchronized (c) {
            // 3. How to allocate work for each thread (recall it is the run function which
            // all the threads execute)

            // Here this code implements the allocated work for perticular thread
            // Each element of the resulting matrix will generate by a perticular thread
            for (s = 0, k = 0; k < z1; k++)
                s += a[i][k] * b[k][j];
            c[i][j] = s;
        }
    }

    public static int[][] returnC() {
        return c;
    }

    public static int[][] multiply(final int[][] a, final int[][] b) {
        /*
         * check if multipication can be done, if not return null allocate required
         * memory return a * b
         */
        final int x = a.length;
        final int y = b[0].length;

        final int z1 = a[0].length;
        final int z2 = b.length;

        if (z1 != z2) {
            System.out.println("Cannnot multiply");
            return null;
        }

        final int[][] c = new int[x][y];
        int i, j;

        // 1. How to use threads to parallelize the operation?
        // Every element in the resulting matrix will be determined by a different
        // thread

        // 2. How may threads to use?
        // x * y threads are used to generate the result.
        for (i = 0; i < x; i++)
            for (j = 0; j < y; j++) {
                try {
                    Matrix temp_thread = new Matrix(a, b, c, i, j, z1);
                    temp_thread.start();

                    // 4. How to synchronize?

                    // synchronized() is used with join() to guarantee that the perticular thread
                    // will be accessed first
                    temp_thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        return Matrix.returnC();
    }
}
```
<p>You can use <code>Main.java</code> to give 2 matrices that need to be multiplied.</p>
<pre class="lang-java prettyprint-override"><code>class Main {
    public static int[][] a = {
            {1, 1, 1},
            {1, 1, 1},
            {1, 1, 1}};

    public static int[][] b = {
            {1},
            {1},
            {1}};

    public static void print_matrix(int[][] a) {
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++)
                System.out.print(a[i][j] + " ");
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] x = Matrix.multiply(a, b);
        print_matrix(x); // see if the multipication is correct
    }
}
</code>```

Body:
I'm trying to create a Java program with threads for matrix multiplication. This is the source code:

import java.util.Random;

public class MatrixTest {
    //Creating the matrix
    static int[][] mat = new int[3][3];
    static int[][] mat2 = new int[3][3];
    static int[][] result = new int[3][3];

    public static void main(String[] args) {
        //Creating the object of random class
        Random rand = new Random();

        //Filling first matrix with random values
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                mat[i][j] = rand.nextInt(10);
            }
        }

        //Filling second matrix with random values
        for (int i = 0; i < mat2.length; i++) {
            for (int j = 0; j < mat2[i].length; j++) {
                mat2[i][j] = rand.nextInt(10);
            }
        }

        try {
            //Object of multiply Class
            Multiply multiply = new Multiply(3, 3);

            //Threads
            MatrixMultiplier thread1 = new MatrixMultiplier(multiply);
            MatrixMultiplier thread2 = new MatrixMultiplier(multiply);
            MatrixMultiplier thread3 = new MatrixMultiplier(multiply);

            //Implementing threads
            Thread th1 = new Thread(thread1);
            Thread th2 = new Thread(thread2);
            Thread th3 = new Thread(thread3);

            //Starting threads
            th1.start();
            th2.start();
            th3.start();

            th1.join();
            th2.join();
            th3.join();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Printing the result
        System.out.println("\n\nResult:");
        for (int i = 0; i < result.length; i++) {
            for (int j = 0; j < result[i].length; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
    }//End main
}//End Class

//Multiply Class
class Multiply extends MatrixTest {
    private int i;
    private int j;
    private int chance;

    public Multiply(int i, int j) {
        this.i = i;
        this.j = j;
        chance = 0;
    }

    //Matrix Multiplication Function
    public synchronized void multiplyMatrix() {
        int sum = 0;
        int a = 0;
        for (a = 0; a < i; a++) {
            sum = 0;
            for (int b = 0; b < j; b++) {
                sum = sum + mat[chance][b] * mat2[b][a];
            }
            result[chance][a] = sum;
        }

        if (chance >= i)
            return;
        chance++;
    }
}//End multiply class

//Thread Class
class MatrixMultiplier implements Runnable {
    private final Multiply mul;

    public MatrixMultiplier(Multiply mul) {
        this.mul = mul;
    }

    @Override
    public void run() {
        mul.multiplyMatrix();
    }
}

I just tried on Eclipse and it works, but now I want to create another version of that program in which, I use one thread for each cell that I'll have on the result matrix. For example I've got two 3x3 matrices. So the result matrix will be 3x3. Then, I want to use 9 threads to calculate each one of the 9 cells of the result matrix.

Can anyone help me?

Body:
Consider Matrix.java and Main.java as follows.

public class Matrix extends Thread {
    private static int[][] a;
    private static int[][] b;
    private static int[][] c;

    /* You might need other variables as well */
    private int i;
    private int j;
    private int z1;

    private int s;
    private int k;

    public Matrix(int[][] A, final int[][] B, final int[][] C, int i, int j, int z1) { // need to change this, might
        // need some information
        a = A;
        b = B;
        c = C;
        this.i = i;
        this.j = j;
        this.z1 = z1; // a[0].length
    }

    public void run() {
        synchronized (c) {
            // 3. How to allocate work for each thread (recall it is the run function which
            // all the threads execute)

            // Here this code implements the allocated work for perticular thread
            // Each element of the resulting matrix will generate by a perticular thread
            for (s = 0, k = 0; k < z1; k++)
                s += a[i][k] * b[k][j];
            c[i][j] = s;
        }
    }

    public static int[][] returnC() {
        return c;
    }

    public static int[][] multiply(final int[][] a, final int[][] b) {
        /*
         * check if multipication can be done, if not return null allocate required
         * memory return a * b
         */
        final int x = a.length;
        final int y = b[0].length;

        final int z1 = a[0].length;
        final int z2 = b.length;

        if (z1 != z2) {
            System.out.println("Cannnot multiply");
            return null;
        }

        final int[][] c = new int[x][y];
        int i, j;

        // 1. How to use threads to parallelize the operation?
        // Every element in the resulting matrix will be determined by a different
        // thread

        // 2. How may threads to use?
        // x * y threads are used to generate the result.
        for (i = 0; i < x; i++)
            for (j = 0; j < y; j++) {
                try {
                    Matrix temp_thread = new Matrix(a, b, c, i, j, z1);
                    temp_thread.start();

                    // 4. How to synchronize?

                    // synchronized() is used with join() to guarantee that the perticular thread
                    // will be accessed first
                    temp_thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        return Matrix.returnC();
    }
}

You can use Main.java to give 2 matrices that need to be multiplied.

class Main {
    public static int[][] a = {
            {1, 1, 1},
            {1, 1, 1},
            {1, 1, 1}};

    public static int[][] b = {
            {1},
            {1},
            {1}};

    public static void print_matrix(int[][] a) {
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++)
                System.out.print(a[i][j] + " ");
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] x = Matrix.multiply(a, b);
        print_matrix(x); // see if the multipication is correct
    }
}


问:
How to bind the useState() in React to dynamically generated
 elements?
I am trying to create a widget in React which has a drop down in each block. I need to show a drop down on the click of a button in each respective list. But what is happening is, when i click the button all the drop down are showing up (of all the dynamically repeated elements).

```<code>class App extends Component {
  render() {
    return (
      <div className="wrapper">
        <div className="widget">
          <h2>whats happeing</h2>
          <Block data={mock} /> //sub component which has the dropdown
        </div>
      </div>
    );
  }
}

const Block = props => {
  let blocks = [];
  let [showDropdown, setShowDropdown] = useState(false); //currently i am trying to get this done with useState()

  if (props.data.length) {
    blocks = props.data.map(function(item) {
      return (
        <div key={item.id} className="block">
          <span
            className="dropdown-btn"
            onClick={() => setShowDropdown(!showDropdown)}
          >
            ▼
          </span>
          <div className="left-col">
            <p>{item.category}</p>
            <h3>
              <a href="#">{item.title}</a>
            </h3>
          </div>
          {showDropdown && <Dropdown />}
        </div>
      );
    });
  }
  return <div>{blocks}</div>;
};
</code>```

This is the sandbox link to the code. Could you please let me know how to handle this in React ?
https://codesandbox.io/s/widget-with-drodown-kjovc

答:
The issue is that you only have 1 visible variable but you really need multiple. If you make a change like the following it will work properly

```<code>const Block = props => {
  let [showDropdown, setShowDropdown] = useState(false);
  const { category, title } = props.block;

  return (
    <>
      <span
        className="dropdown-btn"
        onClick={() => setShowDropdown(!showDropdown)}
      >
        ▼
      </span>
      <div className="left-col">
        <p>{category}</p>
        <h3>
          <a href="#">{title}</a>
        </h3>
      </div>
      {showDropdown && <Dropdown />}
    </>
  );
};

const Blocks = props => {
  let blocks = [];

  if (props.data.length) {
    blocks = props.data.map(function(item) {
      return (
        <div key={item.id} className="block">
          <Block block={item} />
        </div>
      );
    });
  }
  return <div>{blocks}</div>;
};
export default Blocks;
</code>```

Notice how we have moved the visible boolean into its own component

Title: How to bind the useState() in React to dynamically generated <div> elements?

Body:
I am trying to create a widget in React which has a drop down in each block. I need to show a drop down on the click of a button in each respective list. But what is happening is, when i click the button all the drop down are showing up (of all the dynamically repeated elements).

class App extends Component {
  render() {
    return (

whats happeing

          <Block data={mock} /> //sub component which has the dropdown

    );
  }
}

const Block = props => {
  let blocks = [];
  let [showDropdown, setShowDropdown] = useState(false); //currently i am trying to get this done with useState()

  if (props.data.length) {
    blocks = props.data.map(function(item) {
      return (

           setShowDropdown(!showDropdown)}
          >
            ▼

{item.category}

              {item.title}

          {showDropdown && <Dropdown />}

      );
    });
  }
  return
{blocks}
;
};

This is the sandbox link to the code. Could you please let me know how to handle this in React ?
https://codesandbox.io/s/widget-with-drodown-kjovc

Body:
The issue is that you only have 1 visible variable but you really need multiple. If you make a change like the following it will work properly

const Block = props => {
  let [showDropdown, setShowDropdown] = useState(false);
  const { category, title } = props.block;

  return (
    <>
      <span
        className="dropdown-btn"
        onClick={() => setShowDropdown(!showDropdown)}
      >
        ▼
      </span>
      <div className="left-col">
        <p>{category}</p>
        <h3>
          <a href="#">{title}</a>
        </h3>
      </div>
      {showDropdown && <Dropdown />}
    </>
  );
};

const Blocks = props => {
  let blocks = [];

  if (props.data.length) {
    blocks = props.data.map(function(item) {
      return (
        <div key={item.id} className="block">
          <Block block={item} />
        </div>
      );
    });
  }
  return <div>{blocks}</div>;
};
export default Blocks;

Notice how we have moved the visible boolean into its own component


问:
Certificate problems when no domain present in requests on port 443 and 8443
This is the server block I have that handles https connections:

```<code>server {

 listen xxx.xxx.xxx.xxx:443 ssl;
 listen xxx.xxx.xxx.xxx:8443 ssl;
 server_name subd.domain.com;
 proxy_read_timeout 720s;
 proxy_connect_timeout 720s;
 proxy_send_timeout 720s;

 # Add Headers for odoo proxy mode
 proxy_set_header X-Forwarded-Host $host;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header X-Forwarded-Proto $scheme;
 proxy_set_header X-Real-IP $remote_addr;

 # SSL parameters

 ssl_certificate /xxxx.cer ;
 ssl_certificate_key /xxxx.key ;
 ssl_session_timeout 30m;
 ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
 ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
 ssl_prefer_server_ciphers on;

 # log
 access_log /var/log/nginx/xxxx.access.log;
 error_log /var/log/nginx/xxxx.error.log;

  # Redirect requests to backend server
 location / {
   proxy_redirect off;
   proxy_pass http://xxxx;
 }
</code>```

It works fine when I use the domain name in the browser.
The problem is when I use only the IP: https://xxx.xxx.xxx.xxx

Nginx redirects me to the location described in this block, but with no ssl, it says that the certificate is not valid.

My initial thought is that the certificate specifies a domain and it doesn't match with the ip address I'm using (since there is no domain provided).

If this is true why Nginx keeps returning the page content in a unsercure way? I'd like that if nginx can't assume a secure connection in this block it would refuse it in some way.

How could I achieve this behaviour?

答:
As Ivan Shatsky mentions in the comments the content that the server returned was under ssl but the browser identified it as not completely secure because of the host name missing in the request.

What I finally did was to create a server block that uses the current certificates (although don't fit 100%) to listen to ports 8443 and 443 under the ip with no domain and rewrite its requests  with a domain (one that I choosed as a default one).

Body:
This is the server block I have that handles https connections:

server {

 listen xxx.xxx.xxx.xxx:443 ssl;
 listen xxx.xxx.xxx.xxx:8443 ssl;
 server_name subd.domain.com;
 proxy_read_timeout 720s;
 proxy_connect_timeout 720s;
 proxy_send_timeout 720s;

 # Add Headers for odoo proxy mode
 proxy_set_header X-Forwarded-Host $host;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header X-Forwarded-Proto $scheme;
 proxy_set_header X-Real-IP $remote_addr;

 # SSL parameters

 ssl_certificate /xxxx.cer ;
 ssl_certificate_key /xxxx.key ;
 ssl_session_timeout 30m;
 ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
 ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
 ssl_prefer_server_ciphers on;

 # log
 access_log /var/log/nginx/xxxx.access.log;
 error_log /var/log/nginx/xxxx.error.log;

  # Redirect requests to backend server
 location / {
   proxy_redirect off;
   proxy_pass http://xxxx;
 }

It works fine when I use the domain name in the browser.
The problem is when I use only the IP: https://xxx.xxx.xxx.xxx

Nginx redirects me to the location described in this block, but with no ssl, it says that the certificate is not valid.

My initial thought is that the certificate specifies a domain and it doesn't match with the ip address I'm using (since there is no domain provided).

If this is true why Nginx keeps returning the page content in a unsercure way? I'd like that if nginx can't assume a secure connection in this block it would refuse it in some way.

How could I achieve this behaviour?


问:
Integer.toString() acting weird
bit computer in java and i have run into a weird problem. i have a binary number stored as an integer and i needed to convert it to a string but when i do the Integer.toString() returns 9 when i gave it 00000011 but it should have returned 3 right?
here's the function i was making

```<code>static int binToInt(int bin)
{
    String binary = Integer.toString(bin);
    return Integer.parseInt(binary, 2);
}
</code>```

Can someone explain?
i have been trying for over an hour to find a solution. either i find a page with something else or a tutorial of how to use Integer.toString()

答:
Please include a full program, or at least an example where you call your method the next time.

But if you do int val=00000011, then val will be 9, because java treats numbers starting with 0 as octal.

Title: Integer.toString() acting weird

Body:
bit computer in java and i have run into a weird problem. i have a binary number stored as an integer and i needed to convert it to a string but when i do the Integer.toString() returns 9 when i gave it 00000011 but it should have returned 3 right?
here's the function i was making

static int binToInt(int bin)
{
    String binary = Integer.toString(bin);
    return Integer.parseInt(binary, 2);
}

Can someone explain?
i have been trying for over an hour to find a solution. either i find a page with something else or a tutorial of how to use Integer.toString()


问:
Starting a service of another Android app into my own app
I am running a service of an android app from the shell with am startservice. All works as it should.

```<code>am startservice -a com.anotherdeveloper.app.SERVICE --ef a 1 --ef b 2
</code>```

I'm wondering if it is possible to start the service of another android app without being the developer?
According to this link it's possible:
How to start android service from another Android app

But I don't quite get how to do it.

This is the code I'm using in the MainActivity:

```<code>Intent intent = new Intent();
intent.setComponent(new ComponentName("com.anotherdeveloper.app", "com.anotherdeveloper.app.SERVICE"));
ComponentName c = getApplicationContext().startForegroundService(intent);
</code>```

And in the AndroidManifest.xml I've added this:

```<code>  <service
        android:name="com.anotherdeveloper.app.SERVICE"
        android:enabled="true"
        android:exported="true" />
</code>```

But it shows me an error in the manifest because of course Android Studio can't find the package name of this app installed on my phone.

UPDATE

Thanks to @Martin Marconcini, this is the code I'm using:

```<code>  Intent intent = new Intent();
  intent.setComponent(new ComponentName("com.anotherdeveloper.app","com.anotherdeveloper.app.SERVICE"));
  intent.putExtra("cty", 4);
  intent.putExtra("stt", 2);
  startService(intent);
</code>```

And this is the service in the AndroidManifest.xml:

```<code><service name="com.anotherdeveloper.app.General">
  <intent-filter>
    <action name="com.anotherdeveloper.app.SERVICE"/>
  </intent-filter>
  <intent-filter>
    <action name="com.anotherdeveloper.app.SERVICE_ALT"/>
  </intent-filter>
  <intent-filter>
    <action name="com.anotherdeveloper.app.TERMINATE"/>
  </intent-filter>
</service>
</code>```

答:
Short answer: it solely depends on 3rd party decision (what service creators wrote in corresponding android:exported)

More details here: https://developer.android.com/guide/topics/manifest/service-element

Body:
I am running a service of an android app from the shell with am startservice. All works as it should.

am startservice -a com.anotherdeveloper.app.SERVICE --ef a 1 --ef b 2

I'm wondering if it is possible to start the service of another android app without being the developer?
According to this link it's possible:
How to start android service from another Android app

But I don't quite get how to do it.

This is the code I'm using in the MainActivity:

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.anotherdeveloper.app", "com.anotherdeveloper.app.SERVICE"));
ComponentName c = getApplicationContext().startForegroundService(intent);

And in the AndroidManifest.xml I've added this:

  <service
        android:name="com.anotherdeveloper.app.SERVICE"
        android:enabled="true"
        android:exported="true" />

But it shows me an error in the manifest because of course Android Studio can't find the package name of this app installed on my phone.

UPDATE

Thanks to @Martin Marconcini, this is the code I'm using:

  Intent intent = new Intent();
  intent.setComponent(new ComponentName("com.anotherdeveloper.app","com.anotherdeveloper.app.SERVICE"));
  intent.putExtra("cty", 4);
  intent.putExtra("stt", 2);
  startService(intent);

And this is the service in the AndroidManifest.xml:

<service name="com.anotherdeveloper.app.General">
  <intent-filter>
    <action name="com.anotherdeveloper.app.SERVICE"/>
  </intent-filter>
  <intent-filter>
    <action name="com.anotherdeveloper.app.SERVICE_ALT"/>
  </intent-filter>
  <intent-filter>
    <action name="com.anotherdeveloper.app.TERMINATE"/>
  </intent-filter>
</service>


问:
PHP/Javascript toggle function issue
I have a small issue on a PHP and JavaScript page.
What I would like to happen is to have a table of categories where the user can toggle to get access or remove it.

I almost got it to work, except for one tiny issue. When I click to add a right, the fas star button does become black, and the PHP code behind does update the database, but when I click on a star button to remove the user right, the button remains black. The database gets updated when I click remove right, so no issue there. I have been trying many things already, but now I am a bit stuck.
Does anyone have an idea what causes it?

My relevant code :

```<code><table class="table table-bordered table-hover table-striped table-sm">
  <thead>
    <th>Name</th>
    <?php
    foreach($this->jobcategories as $jobcategory):
    ?>
    <th><?=$jobcategory->name?></th>
    <?php endforeach; ?>
  </thead>
  <tbody>
    <?php
    $counter = 0;
    foreach($this->categories as $category): ?>
      <tr data-id="<?=$category->id?>">
        <td><?=$category->name ?></td>
        <?php
        foreach($this->jobcategories as $jobcategory):
        $jobcat = Categories::findRight($category->id,$jobcategory->id);
          ?>
      <td class="text-left">
        <a class="btn btn-sm btn-outline-info mr-1" onclick="toggleJobcategory('<?=$jobcategory->id?>,<?=$jobcategory->name?>,<?=$category->id?>,<?=$counter?>');return false;">
              <i data-id="[<?=$counter?>,<?=$jobcategory->id?>]" class="<?=($jobcategory->id == $jobcat)? 'fas fa-star': 'far fa-star'?>"></i>
            </a>
          </td>
        <?php
        $counter++;
        endforeach; ?>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>
</code>```

My javascript :

```<code>function toggleJobcategory(id,name,cat,counter){
jQuery.ajax({
  url: 'categories/toggleJobcategory',
  method: "POST",
  data : {id : id, name : name, cat : cat, counter : counter},
  success : function(resp) {
    if(resp.success){
      var eli = jQuery('i[data-id="['+resp.counter+','+resp.jobid+']"]');
      var class = (resp.counter,resp.jobid)? 'fas' : 'far';
      eli.removeClass("fas far");
      eli.addClass(class);
      alertMsg(resp.msg,'success');
    } else {
      alertMsg(resp.msg, 'danger');
    }
  }
});
}
</code>```

答:
What I would is not have the onclick handler inline and have the data that it needs as data-attributes.

This process will allow you to not rely on your PHP response to the have the IDs that it needs to control the icon, which is what I'm guessing is the problem. Inline event handlers are generally frowned upon as they are old.

New Link:

```<code><a class="btn btn-sm btn-outline-info mr-1" data-jobcategory_id="<?=$jobcategory->id?>" data-name="<?=$jobcategory->name?>" data-category_id="<?=$category->id?>" data-counter="<?=$counter?>"
</code>```

New Click Handler

```<code>$(document).on("click", ".btn-outline-info", function() {

  let id = $(this).data("jobcategory_id");
  let name = $(this).data("name");
  let cat = $(this).data("category_id");
  let counter = $(this).data("counter");
  let icon = $(this).find("i");

  jQuery.ajax({
    url: 'categories/toggleJobcategory',
    method: "POST",
    data: {
      id: id,
      name: name,
      cat: cat,
      counter: counter
    },
    success: function(resp) {
      if (resp.success) {
        var class = (counter, resp.jobid) ? 'fas' : 'far';
        icon.removeClass("fas far");
        icon.addClass(class);
        alertMsg(resp.msg, 'success');
      } else {
        alertMsg(resp.msg, 'danger');
      }
    }
  });
});
</code>```

Title: PHP/Javascript toggle function issue

Body:
I have a small issue on a PHP and JavaScript page.
What I would like to happen is to have a table of categories where the user can toggle to get access or remove it.

I almost got it to work, except for one tiny issue. When I click to add a right, the fas star button does become black, and the PHP code behind does update the database, but when I click on a star button to remove the user right, the button remains black. The database gets updated when I click remove right, so no issue there. I have been trying many things already, but now I am a bit stuck.
Does anyone have an idea what causes it?

My relevant code :

    Name
    <?php
    foreach($this->jobcategories as $jobcategory):
    ?>
    <?=$jobcategory->name?>
    <?php endforeach; ?>

    <?php
    $counter = 0;
    foreach($this->categories as $category): ?>
      <tr data-id="<?=$category->id?>">
        <?=$category->name ?>
        <?php
        foreach($this->jobcategories as $jobcategory):
        $jobcat = Categories::findRight($category->id,$jobcategory->id);
          ?>

        <a class="btn btn-sm btn-outline-info mr-1" onclick="toggleJobcategory('<?=$jobcategory->id?>,<?=$jobcategory->name?>,<?=$category->id?>,<?=$counter?>');return false;">
              <i data-id="[<?=$counter?>,<?=$jobcategory->id?>]" class="<?=($jobcategory->id == $jobcat)? 'fas fa-star': 'far fa-star'?>">

        <?php
        $counter++;
        endforeach; ?>

    <?php endforeach; ?>

My javascript :

function toggleJobcategory(id,name,cat,counter){
jQuery.ajax({
  url: 'categories/toggleJobcategory',
  method: "POST",
  data : {id : id, name : name, cat : cat, counter : counter},
  success : function(resp) {
    if(resp.success){
      var eli = jQuery('i[data-id="['+resp.counter+','+resp.jobid+']"]');
      var class = (resp.counter,resp.jobid)? 'fas' : 'far';
      eli.removeClass("fas far");
      eli.addClass(class);
      alertMsg(resp.msg,'success');
    } else {
      alertMsg(resp.msg, 'danger');
    }
  }
});
}

Body:
What I would is not have the onclick handler inline and have the data that it needs as data-attributes.

This process will allow you to not rely on your PHP response to the have the IDs that it needs to control the icon, which is what I'm guessing is the problem. Inline event handlers are generally frowned upon as they are old.

New Link:

<a class="btn btn-sm btn-outline-info mr-1" data-jobcategory_id="<?=$jobcategory->id?>" data-name="<?=$jobcategory->name?>" data-category_id="<?=$category->id?>" data-counter="<?=$counter?>"

New Click Handler

$(document).on("click", ".btn-outline-info", function() {

  let id = $(this).data("jobcategory_id");
  let name = $(this).data("name");
  let cat = $(this).data("category_id");
  let counter = $(this).data("counter");
  let icon = $(this).find("i");

  jQuery.ajax({
    url: 'categories/toggleJobcategory',
    method: "POST",
    data: {
      id: id,
      name: name,
      cat: cat,
      counter: counter
    },
    success: function(resp) {
      if (resp.success) {
        var class = (counter, resp.jobid) ? 'fas' : 'far';
        icon.removeClass("fas far");
        icon.addClass(class);
        alertMsg(resp.msg, 'success');
      } else {
        alertMsg(resp.msg, 'danger');
      }
    }
  });
});


问:
UIWebview returns error and adds m. to request URL
I´m trying to load a URL to a webview.

Let´s say the url is: http://www.somepage.com/

But for some reason when I load the url in the webview, it adds a m. (URL looks like this: http://m.somepage.com) , it seems like it´s trying to add a mobile version of the website. There isn´t a mobile version of the website, so it´s trying to load a url that doesn´t exist.

In the shouldStartLoadWithRequest delegate method for the webview, it returns the correct URL. In the didFailWithError method I can an error saying: Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo=0x5a7c670 {NSErrorFailingURLStringKey=http://m.somepage.com

Any idea how I can fix this? Can I replace the m. with www in some way?

答:
This is most certainly an issue with the webserver. It is redirecting your requests to a domain that does not exist. If you have access to the webserver's configuration you will need to fix this there.

If you don't have access to the webserver, your only chance at avoiding this particular issue is to send a different User-Agent string so that the webserver no longer thinks you are viewing the page from a mobile device. However, there doesn't seem to be an easy way to do this on a site-by-site basis.

Relevant Stack Overflow Question:

Change User Agent in UIWebView (iPhone SDK)


问:
Dotnetcore: how to get httpClient from a service reference?
I think I need to figure out how to get the httpclient from a service reference.

I've been connecting to a web service that returns a certificate error.  I want to bypass that error, and in dotnet framework, that's simple.  However, in core, I'm told I have to get the httpClient and add a custom handler to it.  That's fine, but when I have is a service reference object to the web service, and I can't figure out how to get an httpClient from that.

First, I added a service reference to a web service (not one I control).

next,

BasicHttpBinding httpBinding = new BasicHttpBinding();

```<code>    httpBinding.Security.Mode = BasicHttpSecurityMode.Transport;

    httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

    httpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Basic;

        SRI_CAP_AlertCollector.AlertCollectorServicePortClient client = new SRI_CAP_AlertCollector.AlertCollectorServicePortClient(httpBinding, endpoint);
</code>```

but when I call one of the service methods (asynchronously), I get an error because of the certificate.
Since this is a proof-of-concept, I want to bypass the certificate error.

In DotNetCore, doing so is done differently than with dotnet framework.  So I was trying to figure out how to get the httpClientHandler from the service reference so that I can add a ServerCertificateCustomValidationCallback

答:
Since you work with .net core I would suggest that you use HttpClientFactory. Optimally you can register a named client factory in DI container like below.

```<code>services.AddHttpClient("named_client")
                .ConfigurePrimaryHttpMessageHandler(() =>
                {
                var handler = new HttpClientHandler();

                //Get certificate

                X509Certificate2 cert = null;
                //Load your certificate

                if (cert == null) throw new IndexOutOfRangeException($"No certificate found");

                handler.ClientCertificates.Add(cert);
                handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

                return handler;
            });
</code>```

On the code above HttpClientHandler.DangerousAcceptAnyServerCertificateValidator wraps the callback function that returns true.
When you resolve the httpfactory in the class, and you create a new client, you should do it like

```<code>public class ClassResponsibleForHttpCalls
{
    private readonly IHttpClientFactory _clientFactory;

    public ClassResponsibleForHttpCalls(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
    public async Task Get(int id)
    {
        requestMessage.Content.Headers.ContentType.CharSet = "";
        using var client = _clientFactory.CreateClient("named_client");

        //Use your client...
    }
}
</code>```

Use as a parameter the very same name client that you set before.

Body:
I think I need to figure out how to get the httpclient from a service reference.

I've been connecting to a web service that returns a certificate error.  I want to bypass that error, and in dotnet framework, that's simple.  However, in core, I'm told I have to get the httpClient and add a custom handler to it.  That's fine, but when I have is a service reference object to the web service, and I can't figure out how to get an httpClient from that.

First, I added a service reference to a web service (not one I control).

next,

BasicHttpBinding httpBinding = new BasicHttpBinding();

    httpBinding.Security.Mode = BasicHttpSecurityMode.Transport;

    httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

    httpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Basic;

        SRI_CAP_AlertCollector.AlertCollectorServicePortClient client = new SRI_CAP_AlertCollector.AlertCollectorServicePortClient(httpBinding, endpoint);

but when I call one of the service methods (asynchronously), I get an error because of the certificate.
Since this is a proof-of-concept, I want to bypass the certificate error.

In DotNetCore, doing so is done differently than with dotnet framework.  So I was trying to figure out how to get the httpClientHandler from the service reference so that I can add a ServerCertificateCustomValidationCallback

Body:
Since you work with .net core I would suggest that you use HttpClientFactory. Optimally you can register a named client factory in DI container like below.

services.AddHttpClient("named_client")
                .ConfigurePrimaryHttpMessageHandler(() =>
                {
                var handler = new HttpClientHandler();

                //Get certificate

                X509Certificate2 cert = null;
                //Load your certificate

                if (cert == null) throw new IndexOutOfRangeException($"No certificate found");

                handler.ClientCertificates.Add(cert);
                handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

                return handler;
            });

On the code above HttpClientHandler.DangerousAcceptAnyServerCertificateValidator wraps the callback function that returns true.
When you resolve the httpfactory in the class, and you create a new client, you should do it like

public class ClassResponsibleForHttpCalls
{
    private readonly IHttpClientFactory _clientFactory;

    public ClassResponsibleForHttpCalls(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
    public async Task Get(int id)
    {
        requestMessage.Content.Headers.ContentType.CharSet = "";
        using var client = _clientFactory.CreateClient("named_client");

        //Use your client...
    }
}

Use as a parameter the very same name client that you set before.


问:
Configuring Duktape 2.5.0 for use under MacOSX (Catalina)
I am wanting to build Duktape to run under MacOSX.
The instructions here say to run the supplied configuration tool at tools/configure.py
There are different instructions here saying to run tools/genconfig.py

Both scripts fail with

```<code>import yaml
ImportError: No module named yaml
</code>```

There are files in the distribution ending in .yalm but no file of that name.

Any help would be much appreciated.  I have not been able to find any support forum for Duktape.

答: I've moved on from here.  Just compiled Duktape as a single source file with my application and all is good.  Resolved.</p>

Body:
I am wanting to build Duktape to run under MacOSX.
The instructions here say to run the supplied configuration tool at tools/configure.py
There are different instructions here saying to run tools/genconfig.py

Both scripts fail with

import yaml
ImportError: No module named yaml

There are files in the distribution ending in .yalm but no file of that name.

Any help would be much appreciated.  I have not been able to find any support forum for Duktape.


问:
Format java output
I have an O/P from a java class. The O/P needs alignment for more readability. For ex: I get the new line as the character itself '\n' in the O/P and the entire O/P is a continuous string without proper alignment which makes the O/P difficult to read.

Sample O/P

```<code>'comp.db.actionserver.ActionServerResponse'::{
  action:'comp.db.workflow.actions.GetHostMemAllocInfo'::{
    rawOutput:'java.lang.String'::"meminfo::{\n  replicationStoreReader:'18700'::'malloc'::{\n    max :   9580544,\n    alloc : 6679840,\n    free :  348896,\n    frag :  5,\n  },\n  replicationStoreReader:'18700'::'ConnectionQueue'::{\n    max :   3563520,\n    alloc : 1412928,\n    free :  8384,\n    frag :  0,\n  },\n  replicationStoreReader:'18701'::'malloc'::{\n    max :   6295552,\n    alloc : 5779744,\n    free :  446176,\n    frag :  7,\n  },\n  replicationStoreReader:'18701'::'ConnectionQueue'::{\n    max :   1105920,\n    alloc : 44864,\n    free :  1061056,\n    frag :  2365,\n  },\n  storeReader:'30300'::'ConnectionQueue'::{\n    max :   2105344,\n    alloc : 548176,\n    free :  1557168,\n    frag :  284,\n  },\n  storeReader:'30301'::'malloc'::{\n    max :   20574208,\n    alloc : 19905408,\n    free :  668800,\n    frag :  3,\n  },\n  storeReader:'30301'::'ConnectionQueue'::{\n    max :   2105344,\n    alloc : 339632,\n    free :  1765712,\n    frag :  519,\n  },\n}\n2020-06-01T07:42:43.106253\tmain\t0",
    result:'java.lang.String'::"completed",
    returnMessage:'java.lang.String'::"GetHostMemAllocInfo: Action execution successful"
  },
  message:'java.lang.String'::"Action was executed succesfully",
  status:'comp.db.actionserver.ServiceResponse$Status'::"OK"
}
</code>```

I'm looking to put proper alignment in place so that '\n' character actually provides a line break and the tab spaces in the continuous string can be used to properly align the O/P. Something like this

```<code>'comp.db.actionserver.ActionServerResponse'::{
  action:'comp.db.workflow.actions.GetHostMemAllocInfo'::{
    rawOutput:'java.lang.String'::
    "meminfo::{
        replicationStoreReader:'18700'::'malloc'::{
            max :   9580544,
            alloc : 6679840,
            free :  348896,
            frag :  5,
        },
        replicationStoreReader:'18700'::'ConnectionQueue'::{
            max :   3563520,
            alloc : 1412928,
            free :  8384,
            frag :  0,
        },
        replicationStoreReader:'18701'::'malloc'::{
            max :   6295552,
            alloc : 5779744,
            free :  446176,
            frag :  7,
        },
        replicationStoreReader:'18701'::'ConnectionQueue'::{
            max :   1105920,
            alloc : 44864,
            free :  1061056,
            frag :  2365,
        },
        storeReader:'30300'::'ConnectionQueue'::{
            max :   2105344,
            alloc : 548176,
            free :  1557168,
            frag :  284,
        },
        storeReader:'30301'::'malloc'::{
            max :   20574208,
            alloc : 19905408,
            free :  668800,
            frag :  3,
        },
        storeReader:'30301'::'ConnectionQueue'::{
            max :   2105344,
            alloc : 339632,
            free :  1765712,
            frag :  519,
        },
    }
    2020-06-01T07:42:43.106253  main  0",
    result:'java.lang.String'::"completed",
    returnMessage:'java.lang.String'::"GetHostMemAllocInfo: Action execution successful"
  },
  message:'java.lang.String'::"Action was executed succesfully",
  status:'comp.db.actionserver.ServiceResponse$Status'::"OK"
}
</code>```

答:
You can just do something like:
    yourString = yourString.replace("\n", System.lineSeparator());

I'm not sure if you need to escape the **. If so, use \\n and it should work.

Title: Format java output

Body:
I have an O/P from a java class. The O/P needs alignment for more readability. For ex: I get the new line as the character itself '\n' in the O/P and the entire O/P is a continuous string without proper alignment which makes the O/P difficult to read.

Sample O/P

'comp.db.actionserver.ActionServerResponse'::{
  action:'comp.db.workflow.actions.GetHostMemAllocInfo'::{
    rawOutput:'java.lang.String'::"meminfo::{\n  replicationStoreReader:'18700'::'malloc'::{\n    max :   9580544,\n    alloc : 6679840,\n    free :  348896,\n    frag :  5,\n  },\n  replicationStoreReader:'18700'::'ConnectionQueue'::{\n    max :   3563520,\n    alloc : 1412928,\n    free :  8384,\n    frag :  0,\n  },\n  replicationStoreReader:'18701'::'malloc'::{\n    max :   6295552,\n    alloc : 5779744,\n    free :  446176,\n    frag :  7,\n  },\n  replicationStoreReader:'18701'::'ConnectionQueue'::{\n    max :   1105920,\n    alloc : 44864,\n    free :  1061056,\n    frag :  2365,\n  },\n  storeReader:'30300'::'ConnectionQueue'::{\n    max :   2105344,\n    alloc : 548176,\n    free :  1557168,\n    frag :  284,\n  },\n  storeReader:'30301'::'malloc'::{\n    max :   20574208,\n    alloc : 19905408,\n    free :  668800,\n    frag :  3,\n  },\n  storeReader:'30301'::'ConnectionQueue'::{\n    max :   2105344,\n    alloc : 339632,\n    free :  1765712,\n    frag :  519,\n  },\n}\n2020-06-01T07:42:43.106253\tmain\t0",
    result:'java.lang.String'::"completed",
    returnMessage:'java.lang.String'::"GetHostMemAllocInfo: Action execution successful"
  },
  message:'java.lang.String'::"Action was executed succesfully",
  status:'comp.db.actionserver.ServiceResponse$Status'::"OK"
}

I'm looking to put proper alignment in place so that '\n' character actually provides a line break and the tab spaces in the continuous string can be used to properly align the O/P. Something like this

'comp.db.actionserver.ActionServerResponse'::{
  action:'comp.db.workflow.actions.GetHostMemAllocInfo'::{
    rawOutput:'java.lang.String'::
    "meminfo::{
        replicationStoreReader:'18700'::'malloc'::{
            max :   9580544,
            alloc : 6679840,
            free :  348896,
            frag :  5,
        },
        replicationStoreReader:'18700'::'ConnectionQueue'::{
            max :   3563520,
            alloc : 1412928,
            free :  8384,
            frag :  0,
        },
        replicationStoreReader:'18701'::'malloc'::{
            max :   6295552,
            alloc : 5779744,
            free :  446176,
            frag :  7,
        },
        replicationStoreReader:'18701'::'ConnectionQueue'::{
            max :   1105920,
            alloc : 44864,
            free :  1061056,
            frag :  2365,
        },
        storeReader:'30300'::'ConnectionQueue'::{
            max :   2105344,
            alloc : 548176,
            free :  1557168,
            frag :  284,
        },
        storeReader:'30301'::'malloc'::{
            max :   20574208,
            alloc : 19905408,
            free :  668800,
            frag :  3,
        },
        storeReader:'30301'::'ConnectionQueue'::{
            max :   2105344,
            alloc : 339632,
            free :  1765712,
            frag :  519,
        },
    }
    2020-06-01T07:42:43.106253  main  0",
    result:'java.lang.String'::"completed",
    returnMessage:'java.lang.String'::"GetHostMemAllocInfo: Action execution successful"
  },
  message:'java.lang.String'::"Action was executed succesfully",
  status:'comp.db.actionserver.ServiceResponse$Status'::"OK"
}


问:
Generate map tiles with custom data already printed
I'm using Leaflet, with CanvasLayer, to draw a large dataset on a map. Each data point is rendered as a circle with a radial gradient fill, gradient colors depending on each point's data values (4 color for each point).

Data was dynamic at first, but now it became a fixed set of (>1M) points.
What would be a way to draw the data once, save tiles, and then serve them with added data already "printed" on them?
I ideally would like to, for a set of zoom levels, get all the tiles for the interested area, run my draw function (so that I can draw a different gradient for each data point), and finally export tiles with my drawing applied.

答:
I ended up drawing my dataset on tiles with node-canvas. This way I can make a TileLayer in Leaflet which works as an overlay on whatever map I want to render underneath.

node-canvas was the answer for me, because I could use it to draw data the way I wanted, like I would do on an html canvas. Then it was a matter of figuring out tiles and zoom levels:

1.
I used https://github.com/veltman/xyz-affair to know on which tiles my data would fit at a selection of zoom levels

2.
For each zoom level, I've drawn my complete picture (whose size I knew from step 1) and saved each 256x256 region of it as a png tile

3.
I can now serve my static tiles with a web-server, to get them on Leaflet as a TileLayer


问:
How to view data inside IDataView
In ML.net, I want to view the data in the IDataView to verify whether the right data is loaded. I cannot see any visualizer/debugging tool to view them just like we view in System.Data.DataTable as a table

```<code>var mlContext = new MLContext();
IDataView trainData = mlContext.Data.LoadFromTextFile<TaxiTrip>(GetAbsolutePath("../../taxi-fare-test.csv"), hasHeader: true);
</code>```

答:
There's a Preview method for the IDataView. You can run that method in a variable and debug through there to look at the data.

```<code>var preview = trainData.Preview();
</code>```

Title: How to view data inside IDataView

Body:
In ML.net, I want to view the data in the IDataView to verify whether the right data is loaded. I cannot see any visualizer/debugging tool to view them just like we view in System.Data.DataTable as a table

var mlContext = new MLContext();
IDataView trainData = mlContext.Data.LoadFromTextFile<TaxiTrip>(GetAbsolutePath("../../taxi-fare-test.csv"), hasHeader: true);

Body:
There's a Preview method for the IDataView. You can run that method in a variable and debug through there to look at the data.

var preview = trainData.Preview();