问:
Animation not happening as it is supposed to be for subclass of UIView with layers
I am trying to animate a subclass of UIView that has a some layers with shadow. In a view controller, I set this view inside a container. I animate container's height constraint. The container (the purple one in the video) animates properly, but the view that is supposed to be animated, doesn't animate the way it should be.

How it looks now

This is how I animate the container view.

```<code>func updateWhiteCircle(with progressHeight: CGFloat?) {
    guard let progressHeight = progressHeight else {
        return
    }
    neumorphicRingProgressHeightConstraint.constant = progressHeight
    UIView.animate(withDuration: 1.0) { [weak self] in
        self?.view.layoutIfNeeded()
    }
}
</code>```

Where do I get it wrong? Why doesn't it animate the way it should be?

答:
You didn't show us how you're generating the "white shadow," but likely you're setting it in the view's layoutSubviews() func.

The problem is, that does not animate with the size of the view.

You probably want to animate the path for the "shadow layer."

Here's a quick example:

```<code>class WhiteCircleView: UIView {

    private let shapeLayer = CAShapeLayer()

    // public vars so we can set various properties
    public var fillColor: UIColor = .white {
        didSet {
            shapeLayer.fillColor = fillColor.cgColor
        }
    }
    public var shadowColor: UIColor = .white {
        didSet {
            shapeLayer.shadowColor = shadowColor.cgColor
        }
    }
    public var shadowOpacity: Float = 1.0 {
        didSet {
            shapeLayer.shadowOpacity = shadowOpacity
        }
    }
    public var shadowRadius: CGFloat = 20 {
        didSet {
            shapeLayer.shadowRadius = shadowRadius
        }
    }
    public var shadowOffset: CGSize = .zero {
        didSet {
            shapeLayer.shadowOffset = shadowOffset
        }
    }

    public var progress: CGFloat = 0 {
        didSet {
            animCircle()
        }
    }
    private var curProgress: CGFloat = 0

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    private func commonInit() -> Void {
        shapeLayer.fillColor = fillColor.cgColor
        shapeLayer.shadowColor = shadowColor.cgColor
        shapeLayer.shadowOffset = shadowOffset
        shapeLayer.shadowRadius = shadowRadius
        shapeLayer.shadowOpacity = shadowOpacity

        layer.addSublayer(shapeLayer)
    }
    override func layoutSubviews() {
        let w: CGFloat = bounds.width * CGFloat(progress)
        let wi: CGFloat = (bounds.width - w) * 0.5
        let newPath = UIBezierPath(ovalIn: bounds.insetBy(dx: wi, dy: wi)).cgPath
        shapeLayer.path = newPath
    }
    private func animCircle() {
        print(progress)
        let w: CGFloat = bounds.width * CGFloat(progress)
        let wi: CGFloat = (bounds.width - w) * 0.5
        let curPath = shapeLayer.path
        let newPath = UIBezierPath(ovalIn: bounds.insetBy(dx: wi, dy: wi)).cgPath

        CATransaction.begin()

        let animation = CABasicAnimation(keyPath: "path")
        animation.fromValue = curPath
        animation.toValue = newPath
        animation.duration = 0.5
        animation.fillMode = .forwards
        animation.isRemovedOnCompletion = false

        CATransaction.setCompletionBlock({
            // update to new path on anim end
            self.shapeLayer.path = newPath
        })

        shapeLayer.add(animation, forKey: "grow")
        CATransaction.commit()
    }
}

class AnimCircleVC: UIViewController {

    let wcv = WhiteCircleView()

    let bkgColor: UIColor = UIColor(white: 0.75, alpha: 1.0)

    var progress: CGFloat = 0

    // a "center label" to show progress value
    let pLabel: UILabel = {
        let v = UILabel()
        v.backgroundColor = .systemYellow
        v.textAlignment = .center
        v.text = "0%"
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = bkgColor
        wcv.fillColor = bkgColor

        wcv.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(wcv)

        pLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(pLabel)

        let g = view.safeAreaLayoutGuide

        NSLayoutConstraint.activate([
            wcv.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            wcv.centerYAnchor.constraint(equalTo: g.topAnchor, constant: 200.0),
            wcv.heightAnchor.constraint(equalToConstant: 200.0),
            wcv.widthAnchor.constraint(equalTo: wcv.heightAnchor),

            pLabel.centerXAnchor.constraint(equalTo: wcv.centerXAnchor),
            pLabel.centerYAnchor.constraint(equalTo: wcv.centerYAnchor),
            pLabel.widthAnchor.constraint(equalToConstant: 100.0),
            pLabel.heightAnchor.constraint(equalTo: pLabel.widthAnchor),
        ])

        pLabel.layer.cornerRadius = 50.0
        pLabel.layer.masksToBounds = true

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if progress >= 1.0 {
            // shrink it away
            progress = 0.0
        } else {
            if progress == 0.0 {
                // start at 60%
                progress = 0.6
            } else {
                // increment by 10%
                progress += 0.10
            }
        }
        // floating point can result in 0.99999...
        //  so round to 1/100th
        progress = (progress * 100).rounded() / 100.0
        wcv.progress = progress

        pLabel.text = "\(Int(progress * 100))%"
    }

}
</code>```

Body:
I am trying to animate a subclass of UIView that has a some layers with shadow. In a view controller, I set this view inside a container. I animate container's height constraint. The container (the purple one in the video) animates properly, but the view that is supposed to be animated, doesn't animate the way it should be.

How it looks now

This is how I animate the container view.

func updateWhiteCircle(with progressHeight: CGFloat?) {
    guard let progressHeight = progressHeight else {
        return
    }
    neumorphicRingProgressHeightConstraint.constant = progressHeight
    UIView.animate(withDuration: 1.0) { [weak self] in
        self?.view.layoutIfNeeded()
    }
}

Where do I get it wrong? Why doesn't it animate the way it should be?

Body:
You didn't show us how you're generating the "white shadow," but likely you're setting it in the view's layoutSubviews() func.

The problem is, that does not animate with the size of the view.

You probably want to animate the path for the "shadow layer."

Here's a quick example:

class WhiteCircleView: UIView {

    private let shapeLayer = CAShapeLayer()

    // public vars so we can set various properties
    public var fillColor: UIColor = .white {
        didSet {
            shapeLayer.fillColor = fillColor.cgColor
        }
    }
    public var shadowColor: UIColor = .white {
        didSet {
            shapeLayer.shadowColor = shadowColor.cgColor
        }
    }
    public var shadowOpacity: Float = 1.0 {
        didSet {
            shapeLayer.shadowOpacity = shadowOpacity
        }
    }
    public var shadowRadius: CGFloat = 20 {
        didSet {
            shapeLayer.shadowRadius = shadowRadius
        }
    }
    public var shadowOffset: CGSize = .zero {
        didSet {
            shapeLayer.shadowOffset = shadowOffset
        }
    }

    public var progress: CGFloat = 0 {
        didSet {
            animCircle()
        }
    }
    private var curProgress: CGFloat = 0

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    private func commonInit() -> Void {
        shapeLayer.fillColor = fillColor.cgColor
        shapeLayer.shadowColor = shadowColor.cgColor
        shapeLayer.shadowOffset = shadowOffset
        shapeLayer.shadowRadius = shadowRadius
        shapeLayer.shadowOpacity = shadowOpacity

        layer.addSublayer(shapeLayer)
    }
    override func layoutSubviews() {
        let w: CGFloat = bounds.width * CGFloat(progress)
        let wi: CGFloat = (bounds.width - w) * 0.5
        let newPath = UIBezierPath(ovalIn: bounds.insetBy(dx: wi, dy: wi)).cgPath
        shapeLayer.path = newPath
    }
    private func animCircle() {
        print(progress)
        let w: CGFloat = bounds.width * CGFloat(progress)
        let wi: CGFloat = (bounds.width - w) * 0.5
        let curPath = shapeLayer.path
        let newPath = UIBezierPath(ovalIn: bounds.insetBy(dx: wi, dy: wi)).cgPath

        CATransaction.begin()

        let animation = CABasicAnimation(keyPath: "path")
        animation.fromValue = curPath
        animation.toValue = newPath
        animation.duration = 0.5
        animation.fillMode = .forwards
        animation.isRemovedOnCompletion = false

        CATransaction.setCompletionBlock({
            // update to new path on anim end
            self.shapeLayer.path = newPath
        })

        shapeLayer.add(animation, forKey: "grow")
        CATransaction.commit()
    }
}

class AnimCircleVC: UIViewController {

    let wcv = WhiteCircleView()

    let bkgColor: UIColor = UIColor(white: 0.75, alpha: 1.0)

    var progress: CGFloat = 0

    // a "center label" to show progress value
    let pLabel: UILabel = {
        let v = UILabel()
        v.backgroundColor = .systemYellow
        v.textAlignment = .center
        v.text = "0%"
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = bkgColor
        wcv.fillColor = bkgColor

        wcv.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(wcv)

        pLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(pLabel)

        let g = view.safeAreaLayoutGuide

        NSLayoutConstraint.activate([
            wcv.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            wcv.centerYAnchor.constraint(equalTo: g.topAnchor, constant: 200.0),
            wcv.heightAnchor.constraint(equalToConstant: 200.0),
            wcv.widthAnchor.constraint(equalTo: wcv.heightAnchor),

            pLabel.centerXAnchor.constraint(equalTo: wcv.centerXAnchor),
            pLabel.centerYAnchor.constraint(equalTo: wcv.centerYAnchor),
            pLabel.widthAnchor.constraint(equalToConstant: 100.0),
            pLabel.heightAnchor.constraint(equalTo: pLabel.widthAnchor),
        ])

        pLabel.layer.cornerRadius = 50.0
        pLabel.layer.masksToBounds = true

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if progress >= 1.0 {
            // shrink it away
            progress = 0.0
        } else {
            if progress == 0.0 {
                // start at 60%
                progress = 0.6
            } else {
                // increment by 10%
                progress += 0.10
            }
        }
        // floating point can result in 0.99999...
        //  so round to 1/100th
        progress = (progress * 100).rounded() / 100.0
        wcv.progress = progress

        pLabel.text = "\(Int(progress * 100))%"
    }

}


来源: stackexchange

问:
How to get multiple list from one response in App Studio using jq and map? (Active Campaign)
I have following JSON which I get using API. The json has 2 list, 1- main_roles and 2- cc_roles. Using following code I can get 1 list. But I want to get both list in dropdown(display, value).

How can I get both list 1- main_roles and 2- cc_roles in 1 jq using map?

JSON

```<code>{
    "invoice": {
        "invoice_id": "b494a46396e47726873708f71a71a228ba2782fa",
        "main_roles": [
            {
                "name": "Agent"
            },
            {
                "name": "Customer"
            }
        ],
        "cc_roles": [
            {
                "name": "Manager"
            }
        ]
    }
}
</code>```

JSON Code

```<code>"select": {
  "label": "Invoice",
  "form_fields": [
    {
      "label": "Select Role",
      "id": "selectRole",
      "type": "dropdown",
      "required": true,
      "options": {
        "!pipe": [
          {
            "!http": {
              "method": "GET",
              "path": "https://api.test.com/getroles"
            }
          },
          {
            "!jq": ".invoice.main_roles | map({ display: .name , value: .name })"
          }
        ]
      }
    }
  ]
}
</code>```

答:
If you want to get both lists as separate arrays, simply call them one after another, separated by a comma ,:

```<code>.invoice | .main_roles, .cc_roles | map({ display: .name , value: .name })
</code>```

[
  {
    "display": "Agent",
    "value": "Agent"
  },
  {
    "display": "Customer",
    "value": "Customer"
  }
]
[
  {
    "display": "Manager",
    "value": "Manager"
  }
]
```
<p>Demo</p>
<p>If you want them combined into one array, add them together using <code>+</code>:</p>
```.invoice | .main_roles + .cc_roles | map({ display: .name , value: .name })
```
<pre class="lang-json prettyprint-override"><code>[
  {
    "display": "Agent",
    "value": "Agent"
  },
  {
    "display": "Customer",
    "value": "Customer"
  },
  {
    "display": "Manager",
    "value": "Manager"
  }
]
</code>```

Demo

ContentLicense: CC BY-SA 4.0

Body:
I have following JSON which I get using API. The json has 2 list, 1- main_roles and 2- cc_roles. Using following code I can get 1 list. But I want to get both list in dropdown(display, value).

How can I get both list 1- main_roles and 2- cc_roles in 1 jq using map?

JSON

{
    "invoice": {
        "invoice_id": "b494a46396e47726873708f71a71a228ba2782fa",
        "main_roles": [
            {
                "name": "Agent"
            },
            {
                "name": "Customer"
            }
        ],
        "cc_roles": [
            {
                "name": "Manager"
            }
        ]
    }
}

JSON Code

"select": {
  "label": "Invoice",
  "form_fields": [
    {
      "label": "Select Role",
      "id": "selectRole",
      "type": "dropdown",
      "required": true,
      "options": {
        "!pipe": [
          {
            "!http": {
              "method": "GET",
              "path": "https://api.test.com/getroles"
            }
          },
          {
            "!jq": ".invoice.main_roles | map({ display: .name , value: .name })"
          }
        ]
      }
    }
  ]
}

Body:
If you want to get both lists as separate arrays, simply call them one after another, separated by a comma ,:

.invoice | .main_roles, .cc_roles | map({ display: .name , value: .name })

[
  {
    "display": "Agent",
    "value": "Agent"
  },
  {
    "display": "Customer",
    "value": "Customer"
  }
]
[
  {
    "display": "Manager",
    "value": "Manager"
  }
]

Demo

If you want them combined into one array, add them together using +:

.invoice | .main_roles + .cc_roles | map({ display: .name , value: .name })

[
  {
    "display": "Agent",
    "value": "Agent"
  },
  {
    "display": "Customer",
    "value": "Customer"
  },
  {
    "display": "Manager",
    "value": "Manager"
  }
]

Demo


问:
Change color of primeng input-switch
I have the following p-inputSwitch.

```<code><p-inputSwitch class="ml-1 mr-1 align-middle"
               (onChange)="setDefaultValues($event)"
               [ngModel]="defaultValuesToggle">
</p-inputSwitch>

</code>```

Is there a way to change the color from blue when selected? I have tried the following, but nothing changes the color:

```<code>.p-inputswitch {
    background: red !important;
}
.p-inputswitch .p-inputswitch-slider {
  background: red !important;
}
</code>```

答:
You need to add the "selected" state to the selector by adding the class p-inputswitch-checked to .p-inputswitch and also add ::ng-deep infront of the selector to penetrate View Encapsulation:

```<code>::ng-deep .p-inputswitch.p-inputswitch-checked .p-inputswitch-slider {
  background: purple;
}
</code>```

Title: Change color of primeng input-switch

Body:
I have the following p-inputSwitch.

Is there a way to change the color from blue when selected? I have tried the following, but nothing changes the color:

.p-inputswitch {
    background: red !important;
}
.p-inputswitch .p-inputswitch-slider {
  background: red !important;
}

Body:
You need to add the "selected" state to the selector by adding the class p-inputswitch-checked to .p-inputswitch and also add ::ng-deep infront of the selector to penetrate View Encapsulation:

::ng-deep .p-inputswitch.p-inputswitch-checked .p-inputswitch-slider {
  background: purple;
}


问:
ListView with an extra argument
I want to add a parameter somevar to my listview:

```<code>{% url 'products' somevar %}?"
</code>```

in the urls:

```<code>path("products/<int:somevar>", ProductListView.as_view(), name = 'products'),
</code>```

in the views:

```<code>class ProductListView(ListView):
    def get_template_names(self):
        print(self.kwargs) # {"somevar": xxxxx}
        return f"{TEMPLATE_ROOT}/products.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        self.get_products().order_by("number")
        print(kwargs) # kwargs is {} here
        return context

    def get_queryset(self):
        return super().get_queryset().order_by("number")
</code>```

How can I pass the variable to the get_context_data method? I tried defining a get method and call self.get_context_data(**kwargs) within, but this leads to an object has no attribute 'object_list' error.

答:
The View class has different kwargs than the get_context_data method

The kwargs of a View contain the URL Parameters

The kwargs passed to the get_context_data method are passed to the template for rendering

Since you want to access a URL Parameter in get_context_data you would use self.kwargs (self is referring to your View class)

Title: ListView with an extra argument

Body:
I want to add a parameter somevar to my listview:

{% url 'products' somevar %}?"

in the urls:

path("products/<int:somevar>", ProductListView.as_view(), name = 'products'),

in the views:

class ProductListView(ListView):
    def get_template_names(self):
        print(self.kwargs) # {"somevar": xxxxx}
        return f"{TEMPLATE_ROOT}/products.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        self.get_products().order_by("number")
        print(kwargs) # kwargs is {} here
        return context

    def get_queryset(self):
        return super().get_queryset().order_by("number")

How can I pass the variable to the get_context_data method? I tried defining a get method and call self.get_context_data(**kwargs) within, but this leads to an object has no attribute 'object_list' error.


问:
Flatbuffers converting json to binary - unexpected force_align value
I convert a binary file to json with the following command with flatbuffers.

```<code>flatc --json  schema.fbs -- model.blob
</code>```

When I try to immediately convert the json back to a binary with this command

```<code>flatc -b schema.fbs model.json
</code>```

It throws an error

```<code>error: unexpected force_align value '64', alignment must be a power of two integer ranging from the type's natural alignment 1 to 16
</code>```

It points to the very last line of the json file as the problem. Does anybody know the problem? Could it be escape sequences?

答: Is there a force_align: 64 somewhere in schema.fbs ? That would be the real source of the problem. It ignores this attribute when generating the JSON, but i

Body:
I convert a binary file to json with the following command with flatbuffers.

flatc --json  schema.fbs -- model.blob

When I try to immediately convert the json back to a binary with this command

flatc -b schema.fbs model.json

It throws an error

error: unexpected force_align value '64', alignment must be a power of two integer ranging from the type's natural alignment 1 to 16

It points to the very last line of the json file as the problem. Does anybody know the problem? Could it be escape sequences?


问:
How to use quotes in PHP code in PhpStorm on Ubuntu
I'm using a Logitech K120 keyboard (105 keys) on Ubuntu 20.04 and in all other applications I can use the quotes (double and single), but in PhpStorm I can't. It happens to me with quotes and other characters like '~'.

What should I do? I have already used dpkg-reconfigure locales and it still doesn't work.

答:
I had the same problem and found the solution in this issue:
https://youtrack.jetbrains.com/issue/IDEA-78860

You must change the IBUS setting on the keyboard. I did it in the same graphical mode without using any commands (I'm not very good at that yet).

PS: You must restart the PC or at least log out.

I hope it works for you.


问:
How to get Android crash logs?
I have an app that is not in the market place (signed with a debug certificate), but would like to get crash log data, whenever my application crashes. Where can I find a log of why my app crashed?</p>

答:
Here is another solution for Crash Log.

Android market has tool named "Crash Collector"

check following link for more information

http://kpbird.blogspot.com/2011/08/android-application-crash-logs.html

ContentLicense: CC BY-SA 2.5

Title: How to get Android crash logs?

ContentLicense: CC BY-SA 3.0


问:
What am I missing in defining an array?
I have been trying to learn arrays and I can't seem to define an array.

```<code>const int size = 10;
??[size];
</code>```

Can anybody spot my mistakes? Thank You.

答:
```<code>const int size = 10;
type array[size];
</code>```

Is what you want. Substitute type for any type (i.e. int, float, bool etc.).

In this case, specifying array size using a const variable is valid, but there are many cases where it isn't. You'd probably want to learn the difference between const and constexpr.

Also, instead of learning by asking questions here, try finding a good c++ source: a book, online article series or a video tutorial. It'll definitely accelerate your education.

Title: What am I missing in defining an array?

Body:
I have been trying to learn arrays and I can't seem to define an array.

const int size = 10;
??[size];

Can anybody spot my mistakes? Thank You.

Body:
const int size = 10;
type array[size];

Is what you want. Substitute type for any type (i.e. int, float, bool etc.).

In this case, specifying array size using a const variable is valid, but there are many cases where it isn't. You'd probably want to learn the difference between const and constexpr.

Also, instead of learning by asking questions here, try finding a good c++ source: a book, online article series or a video tutorial. It'll definitely accelerate your education.


问:
How to start a REPL while debugging C++?
How can I get a REPL to evaluate simple things and test things out in the middle of a program's execution in C++?

I have some debugging tools at my disposal, lldb, but as far as I can tell, I can only view things, not test new things on the fly, even though it seems like it should be able to do it but maybe that functionality of the lldb debugger only works for Swift.

It doesn't have to be a complete REPL, but the ability to do some basic things would be so incredibly helpful. I am working with a massive binary in a new codebase with all sorts of types, classes, composition, and inheritance going on that's overwhelming and undocumented, and every test and repeat of the 50GB binary is about 10 minutes which is painful (running unit tests takes the same 10 minutes). It would be great if I could test statements out in a REPL on a breakpoint in the middle of the execution, one statement after another to play around and figure things out faster.

I'm coming from a drop into ipython/ipdb background, as well as the same lldb for Swift. Very new to C++.

答:
The lldb command expr - aliased to p - should do what you want.  expr will run the code you provide "as though it had been inserted in the current context" and will return the expression's result.  So for instance, if you have a function and want to see what it returns for various inputs, you can do:

```<code>(lldb) expr my_new_function(10, 20, 30)
</code>```

You can even debug functions while handling such interesting inputs by doing:

```<code>(lldb) break set -n my_new_function
(lldb) expr -i 0 -- my_new_function(10, 20, 30)
</code>```

the -i tells lldb to stop on the breakpoint, by default lldb ignores breakpoints in hand called functions.

You can also define new objects & structs in the expression command, but unlike the Swift REPL mode(*) user-defined objects, functions & variables have to be named with an initial $ to keep them from getting confused with names from your code.  For instance, if you have a class A:

```<code>(lldb) expr A $myA()
</code>```

will make a default-constructed object of type A, then you can call methods on it:

```<code>(lldb) expr $myA().doSomething()
</code>```

Note that C++ templates are poorly described in debug information - the current standard only describes instantiations and not the abstract template form.  So YMMV when trying to create objects of complex template types.  The other danger with C++ is that some functions you want to call may only exist as inlined code, which the debugger can't invoke.  This happens for some of the STL types, e.g. the size() method is often not callable on vectors & the like because it's always inlined.  That's less of a problem with -O0 code, however.

(*) When you run swift in Terminal w/o arguments to bring up the Swift REPL, you are actually just running lldb in a fancy input mode that feeds what you type to the expr command under the covers.  The main difference between the bare expr and the full Swift REPL is that the REPL is focused on making new code, whereas expr is more meant for exploring the code you are stopped in right now, so the name lookup rules are different.  There isn't a full C++ REPL mostly because we don't know how to do jobs like "build C++ classes incrementally", which would be required for a real REPL.

Body:
The lldb command expr - aliased to p - should do what you want.  expr will run the code you provide "as though it had been inserted in the current context" and will return the expression's result.  So for instance, if you have a function and want to see what it returns for various inputs, you can do:

(lldb) expr my_new_function(10, 20, 30)

You can even debug functions while handling such interesting inputs by doing:

(lldb) break set -n my_new_function
(lldb) expr -i 0 -- my_new_function(10, 20, 30)

the -i tells lldb to stop on the breakpoint, by default lldb ignores breakpoints in hand called functions.

You can also define new objects & structs in the expression command, but unlike the Swift REPL mode(*) user-defined objects, functions & variables have to be named with an initial $ to keep them from getting confused with names from your code.  For instance, if you have a class A:

(lldb) expr A $myA()

will make a default-constructed object of type A, then you can call methods on it:

(lldb) expr $myA().doSomething()

Note that C++ templates are poorly described in debug information - the current standard only describes instantiations and not the abstract template form.  So YMMV when trying to create objects of complex template types.  The other danger with C++ is that some functions you want to call may only exist as inlined code, which the debugger can't invoke.  This happens for some of the STL types, e.g. the size() method is often not callable on vectors & the like because it's always inlined.  That's less of a problem with -O0 code, however.

(*) When you run swift in Terminal w/o arguments to bring up the Swift REPL, you are actually just running lldb in a fancy input mode that feeds what you type to the expr command under the covers.  The main difference between the bare expr and the full Swift REPL is that the REPL is focused on making new code, whereas expr is more meant for exploring the code you are stopped in right now, so the name lookup rules are different.  There isn't a full C++ REPL mostly because we don't know how to do jobs like "build C++ classes incrementally", which would be required for a real REPL.


问:
Retrieving data from another column based on entries in another column within same table
I have this table.

```<code>+----+-----------+--------+----------+
| sku|  strength |  color | option_1 |
+----+-----------+--------+----------+
|  1 | 40 lb     | (NULL) | strength |
|  2 | 50 lb     | black  | color    |
|  3 | (NULL)    | black  | color    |
|  4 | (NULL)    | red    | color    |
+----+-----------+--------+----------+
</code>```

I want this table:

```<code>+----+-----------+--------+----------+----------------+
|sku | strength  | color  | option_1 | option_value_1 |
+----+-----------+--------+----------+----------------+
|  1 | 40 lb     | (NULL) | strength | 40 lb          |
|  2 | 50 lb     | black  | color    | black          |
|  3 | (NULL)    | black  | color    | black          |
|  4 | (NULL)    | red    | color    | red            |
+----+-----------+--------+----------+----------------+
</code>```

I'm new to mysql. I'm trying to do this index-match or vlookup like query where option_1 determines which column to retrieve data from and send to option_value_1. I wasn't sure if I should do an inner join or a case clause since I have a much larger table with a lot more options than just color and strength.

答:
You can use a simple searched case expression, such as

```<code>case option_1
  when 'strength' then strength
  when 'color' then color
  when '...' then ...
else 'default option'
end as option_value_1
...
</code>```

Body:
I have this table.

+----+-----------+--------+----------+
| sku|  strength |  color | option_1 |
+----+-----------+--------+----------+
|  1 | 40 lb     | (NULL) | strength |
|  2 | 50 lb     | black  | color    |
|  3 | (NULL)    | black  | color    |
|  4 | (NULL)    | red    | color    |
+----+-----------+--------+----------+

I want this table:

+----+-----------+--------+----------+----------------+
|sku | strength  | color  | option_1 | option_value_1 |
+----+-----------+--------+----------+----------------+
|  1 | 40 lb     | (NULL) | strength | 40 lb          |
|  2 | 50 lb     | black  | color    | black          |
|  3 | (NULL)    | black  | color    | black          |
|  4 | (NULL)    | red    | color    | red            |
+----+-----------+--------+----------+----------------+

I'm new to mysql. I'm trying to do this index-match or vlookup like query where option_1 determines which column to retrieve data from and send to option_value_1. I wasn't sure if I should do an inner join or a case clause since I have a much larger table with a lot more options than just color and strength.

Body:
You can use a simple searched case expression, such as

case option_1
  when 'strength' then strength
  when 'color' then color
  when '...' then ...
else 'default option'
end as option_value_1
...


问:
Xamarin Async deadlock - Cannot get data from API
Im trying to connect to an API and get the data from the "User" table so that the credentials can be authenticated. However after executing GetAsync() the app stucks in a deadlock and doesnt do anything. I have tested the API with postman and it works.</p>
```<code>public async Task<User> UserCredentialsGet(string name, string password)
    {
        var user = new User();
        HttpClient client = new HttpClient();

        string url = "https://xxx.xxx.xxx.xxx:xxxx/api/Users/username=" + name + "/" + "password=" + password ;
        Uri uri = new Uri(url);
        try
        {
            var response = await client.GetAsync(uri).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                string content = response.Content.ReadAsStringAsync().Result;
                user = JsonConvert.DeserializeObject<User>(content);
            }
        }
        catch (Exception ex)
        {

        }

        return user;
        //return await Task.FromResult(user);
    }
</code>```

答:
GetAsync is Idisposable so try to use something like

```<code>    `using (HttpClient client = new HttpClient())
        {
            using (HttpResponseMessage response = await client.GetAsync(uri, cancellationToken))
            {
                var stringResponse = await response.Content.ReadAsStringAsync();
                //todo process response
            }
        }
`
</code>```

For me it works fine.
Do not for forget await response

Body:
Im trying to connect to an API and get the data from the "User" table so that the credentials can be authenticated. However after executing GetAsync() the app stucks in a deadlock and doesnt do anything. I have tested the API with postman and it works.

public async Task<User> UserCredentialsGet(string name, string password)
    {
        var user = new User();
        HttpClient client = new HttpClient();

        string url = "https://xxx.xxx.xxx.xxx:xxxx/api/Users/username=" + name + "/" + "password=" + password ;
        Uri uri = new Uri(url);
        try
        {
            var response = await client.GetAsync(uri).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                string content = response.Content.ReadAsStringAsync().Result;
                user = JsonConvert.DeserializeObject<User>(content);
            }
        }
        catch (Exception ex)
        {

        }

        return user;
        //return await Task.FromResult(user);
    }

Body:
GetAsync is Idisposable so try to use something like

    `using (HttpClient client = new HttpClient())
        {
            using (HttpResponseMessage response = await client.GetAsync(uri, cancellationToken))
            {
                var stringResponse = await response.Content.ReadAsStringAsync();
                //todo process response
            }
        }
`

For me it works fine.
Do not for forget await response


问:
binance websocket not responding to ping
Using gorilla/websocket I dial the binance websocket endpoint, which succeeds without error. After setting the pong handler on the connection, I write a ping control message and wait for a pong to arrive at the pong handler, which never seems to happen. I use a channel, a context with timeout and a select block to check if the pong arrived.

The code:

```<code>package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/gorilla/websocket"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    conn, resp, err := websocket.DefaultDialer.DialContext(ctx, "wss://stream.binance.com:9443/ws", nil)
    if resp != nil {
        log.Printf("status: %s", resp.Status)
    }

    if err != nil {
        panic(err)
    }

    pong := make(chan struct{})
    conn.SetPongHandler(func(appData string) error {
        log.Println(appData)

        pong <- struct{}{}
        return nil
    })

    if err := conn.WriteControl(websocket.PingMessage, []byte("Hello, world!"), time.Now().Add(5*time.Second)); err != nil {
        panic(err)
    }

    select {
    case <-ctx.Done():
        panic(fmt.Errorf("pong wait: %w", ctx.Err()))
    case <-pong:
    }
}
</code>```

Output:

```<code>$ go run ./cmd/ping
2022/02/07 20:01:23 status: 101 Switching Protocols
panic: pong wait: context deadline exceeded

goroutine 1 [running]:
main.main()
        /workspaces/yatgo/cmd/ping/ping.go:39 +0x2ba
exit status 2
</code>```

As per rfc6455, section-5.5.2:

5.5.2.  Ping

The Ping frame contains an opcode of 0x9.

A Ping frame MAY include "Application data".

Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
response, unless it already received a Close frame.  It SHOULD

respond with Pong frame as soon as is practical.  Pong frames are

discussed in Section 5.5.3.

An endpoint MAY send a Ping frame any time after the connection is
established and before the connection is closed.

NOTE: A Ping frame may serve either as a keepalive or as a means to
verify that the remote endpoint is still responsive.

I kind off expected this to work. Binance websocket API limits doc does mentions ping messages:

WebSocket connections have a limit of 5 incoming messages per second. A message is considered:

A PING frame

So I wonder:

Is something wrong with my code?

Or is binance not respecting RFC6455?

答:
The Gorilla Websocket documentation says:

The application must read the connection to process close, ping and pong messages sent from the peer. If the application is not otherwise interested in messages from the peer, then the application should start a goroutine to read and discard messages from the peer.

Fix the application by starting a goroutine to read the connection before the select statement:

```<code>go func() {
    defer cancel()
    for {
        if _, _, err := conn.NextReader(); err != nil {
            fmt.Println(err)
            return
        }
    }
}()

select {
⋮
</code>```

This is a fix for the application shown in the question.  If your actual application reads data from the connection in a loop, then you should not add the goroutine shown here. The application should use one read loop to handle control and data messages.

Body:
Using gorilla/websocket I dial the binance websocket endpoint, which succeeds without error. After setting the pong handler on the connection, I write a ping control message and wait for a pong to arrive at the pong handler, which never seems to happen. I use a channel, a context with timeout and a select block to check if the pong arrived.

The code:

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/gorilla/websocket"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    conn, resp, err := websocket.DefaultDialer.DialContext(ctx, "wss://stream.binance.com:9443/ws", nil)
    if resp != nil {
        log.Printf("status: %s", resp.Status)
    }

    if err != nil {
        panic(err)
    }

    pong := make(chan struct{})
    conn.SetPongHandler(func(appData string) error {
        log.Println(appData)

        pong <- struct{}{}
        return nil
    })

    if err := conn.WriteControl(websocket.PingMessage, []byte("Hello, world!"), time.Now().Add(5*time.Second)); err != nil {
        panic(err)
    }

    select {
    case <-ctx.Done():
        panic(fmt.Errorf("pong wait: %w", ctx.Err()))
    case <-pong:
    }
}

Output:

$ go run ./cmd/ping
2022/02/07 20:01:23 status: 101 Switching Protocols
panic: pong wait: context deadline exceeded

goroutine 1 [running]:
main.main()
        /workspaces/yatgo/cmd/ping/ping.go:39 +0x2ba
exit status 2

As per rfc6455, section-5.5.2:

5.5.2.  Ping

The Ping frame contains an opcode of 0x9.

A Ping frame MAY include "Application data".

Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
response, unless it already received a Close frame.  It SHOULD

respond with Pong frame as soon as is practical.  Pong frames are

discussed in Section 5.5.3.

An endpoint MAY send a Ping frame any time after the connection is
established and before the connection is closed.

NOTE: A Ping frame may serve either as a keepalive or as a means to
verify that the remote endpoint is still responsive.

I kind off expected this to work. Binance websocket API limits doc does mentions ping messages:

WebSocket connections have a limit of 5 incoming messages per second. A message is considered:

A PING frame

So I wonder:

Is something wrong with my code?

Or is binance not respecting RFC6455?

Body:
The Gorilla Websocket documentation says:

The application must read the connection to process close, ping and pong messages sent from the peer. If the application is not otherwise interested in messages from the peer, then the application should start a goroutine to read and discard messages from the peer.

Fix the application by starting a goroutine to read the connection before the select statement:

go func() {
    defer cancel()
    for {
        if _, _, err := conn.NextReader(); err != nil {
            fmt.Println(err)
            return
        }
    }
}()

select {
⋮

This is a fix for the application shown in the question.  If your actual application reads data from the connection in a loop, then you should not add the goroutine shown here. The application should use one read loop to handle control and data messages.


问:
Mootools get the child-index of an element from its parent
I am using event delegation in mootools.  I want to know the row number that has been clicked.  My solution is shown in this jsfiddle: Is there a better way than what I am currently doing?

My approach was to compare the elements until i found the match.  Is there an IndexOf method I could use?

(The following is the data from the jsfiddle for the future)

HTML:

```<code><div id="Record_List">
    <div class="Row">
        <input type="submit" name="Row" value="Edit"/>
    </div>
    <div class="Row">
        <input type="submit" name="Row" value="Edit"/>
    </div>
</div>
</code>```

Javascript:

```<code>window.addEvent(
    'domready',
    function()
    {
        $('Record_List').addEvent(
            'click:relay(input)',
            function(evt, target)
            {
                evt.stop();

                var rowElem = target.getParent();
                var rowNumber = -1;

                $('Record_List').getChildren('div.Row').each(
                    function (el, num)
                    {
                        if (rowElem === el)
                        {
                            rowNumber = num;
                        }
                    });

                // Find the position of the row and display it here:
                alert('Row number: ' + rowNumber);
            });
    });
</code>```

答:
This is pretty hacky, but you can always use Array.prototype's indexOf...

```<code>Array.prototype.indexOf.call(list-o-children, elem-to-find)
</code>```

Body:
I am using event delegation in mootools.  I want to know the row number that has been clicked.  My solution is shown in this jsfiddle: Is there a better way than what I am currently doing?

My approach was to compare the elements until i found the match.  Is there an IndexOf method I could use?

(The following is the data from the jsfiddle for the future)

HTML:

        <input type="submit" name="Row" value="Edit"/>

        <input type="submit" name="Row" value="Edit"/>

Javascript:

window.addEvent(
    'domready',
    function()
    {
        $('Record_List').addEvent(
            'click:relay(input)',
            function(evt, target)
            {
                evt.stop();

                var rowElem = target.getParent();
                var rowNumber = -1;

                $('Record_List').getChildren('div.Row').each(
                    function (el, num)
                    {
                        if (rowElem === el)
                        {
                            rowNumber = num;
                        }
                    });

                // Find the position of the row and display it here:
                alert('Row number: ' + rowNumber);
            });
    });

Body:
This is pretty hacky, but you can always use Array.prototype's indexOf...

Array.prototype.indexOf.call(list-o-children, elem-to-find)


问:
MySQL Could Not Process Parameters
So I have data in a 2 Dimensional Array, and I am trying to insert it into my SQL Database.

```<code>for scrapeddata in range(len(all_images)):
    mycursor.execute('SELECT * FROM ScrapedBooks WHERE BookLink = %s',( all_images[scrapeddata][3],))
    img_link_table = mycursor.fetchall()
    if len(img_link_table)==0:
        HoldBookTitle = [all_images[scrapeddata][0], all_images[scrapeddata][2],all_images[scrapeddata][1],all_images[scrapeddata][3]]

        mycursor.executemany("INSERT INTO ScrapedBooks(BookName, Price, ImageLink, BookLink) VALUES(%s,%s,%s,%s)", (HoldBookTitle))
        mydb.commit()
</code>```

Error:

```<code>mycursor.executemany("INSERT INTO ScrapedBooks(BookName, Price, ImageLink, BookLink) VALUES(%s,%s,%s,%s)", (HoldBookTitle))

File"C:\Users\msala\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\cursor_cext.py", line 355, in executemany
    stmt = self._batch_insert(operation, seq_params)

  File "C:\Users\msala\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\cursor_cext.py", line 333, in _batch_insert
    raise errors.InterfaceError(

mysql.connector.errors.InterfaceError: Failed executing the operation; Could not process parameters
</code>```

I plan to use the saved data in the database in my HTML code for my website, if you guys have any idea on how to do that, please do help me. Thank you!

答:
Array can't be handled that way, but you can make an array of lists and add that ion one go into the database</p>
```<code>all_images = []
HoldBookTitle = []

for scrapeddata in range(len(all_images)):
    mycursor.execute('SELECT * FROM ScrapedBooks WHERE BookLink = %s',( all_images[scrapeddata][3],))
    img_link_table = mycursor.fetchall()
    if len(img_link_table)>0:
        HoldBookTitle.append( (all_images[scrapeddata][0], all_images[scrapeddata][2],all_images[scrapeddata][1],all_images[scrapeddata][3]))
if not HoldBookTitle:
    mycursor.executemany("INSERT INTO ScrapedBooks(BookName, Price, ImageLink, BookLink) VALUES(%s,%s,%s,%s)", HoldBookTitle)
    mydb.commit()
</code>```

Title: MySQL Could Not Process Parameters

Body:
So I have data in a 2 Dimensional Array, and I am trying to insert it into my SQL Database.

for scrapeddata in range(len(all_images)):
    mycursor.execute('SELECT * FROM ScrapedBooks WHERE BookLink = %s',( all_images[scrapeddata][3],))
    img_link_table = mycursor.fetchall()
    if len(img_link_table)==0:
        HoldBookTitle = [all_images[scrapeddata][0], all_images[scrapeddata][2],all_images[scrapeddata][1],all_images[scrapeddata][3]]

        mycursor.executemany("INSERT INTO ScrapedBooks(BookName, Price, ImageLink, BookLink) VALUES(%s,%s,%s,%s)", (HoldBookTitle))
        mydb.commit()

Error:

mycursor.executemany("INSERT INTO ScrapedBooks(BookName, Price, ImageLink, BookLink) VALUES(%s,%s,%s,%s)", (HoldBookTitle))

File"C:\Users\msala\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\cursor_cext.py", line 355, in executemany
    stmt = self._batch_insert(operation, seq_params)

  File "C:\Users\msala\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\cursor_cext.py", line 333, in _batch_insert
    raise errors.InterfaceError(

mysql.connector.errors.InterfaceError: Failed executing the operation; Could not process parameters

I plan to use the saved data in the database in my HTML code for my website, if you guys have any idea on how to do that, please do help me. Thank you!

Body:
Array can't be handled that way, but you can make an array of lists and add that ion one go into the database

all_images = []
HoldBookTitle = []

for scrapeddata in range(len(all_images)):
    mycursor.execute('SELECT * FROM ScrapedBooks WHERE BookLink = %s',( all_images[scrapeddata][3],))
    img_link_table = mycursor.fetchall()
    if len(img_link_table)>0:
        HoldBookTitle.append( (all_images[scrapeddata][0], all_images[scrapeddata][2],all_images[scrapeddata][1],all_images[scrapeddata][3]))
if not HoldBookTitle:
    mycursor.executemany("INSERT INTO ScrapedBooks(BookName, Price, ImageLink, BookLink) VALUES(%s,%s,%s,%s)", HoldBookTitle)
    mydb.commit()


问:
How to obtain bluetooth port direction with pyserial?
I'm trying to connect to an RN42, module through python. When the RN42 pairs with W10 it creates two virtual COM ports(outgoing and incoming). I need to connect to the outgoing port.

I'm trying to do this automatically. I've tried:

```<code>import serial
import serial.tools.list_ports as port_lst

ports = list(port_lst.comports())
bluetooth_ports = []
for p in ports:
    if 'Bluetooth' in p.description:
        bluetooth_ports += [p.device]
bluetooth_com = serial.Serial(bluetooth_ports[0],115200)
</code>```

I thought that the first port was usually the outgoing one, but I've paired the module to another computer, and this didn't apply (the second port was the outgoing one). Is there a way to find out the direction of the COM ports?

Thanks!!!

答:
Although this is an antique question, I have been searching for the answer to this for some time myself and since I finally figured it out I wanted others to be able to find the answer. With help from a blog entry at in the hand and its accompanying gist:

The trick is to acquire the hwid using pySerial, then parse the address. The incoming port in a pair has an address of zero and the outgoing port has a nonzero address. Here is some ugly Python code that decodes it:

```<code>import serial.tools.list_ports
cp=serial.tools.list_ports.comports()
for p in cp:
    if "BTHENUM" in p.hwid:
        start_of_address=p.hwid.rfind("&")
        end_of_address=p.hwid.rfind("_")
        address=p.hwid[start_of_address+1:end_of_address]
        if int(address,16)==0:
            port_type="incoming"
        else:
            port_type="outgoing"
        print(p.hwid)
        print(p.name, address, port_type)
</code>```

And the output:

```<code>BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\7&CC47540&0&000000000000_000000A8
COM4 000000000000 incoming
BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0002\7&CC47540&0&209BA5420081_C00000000
COM5 209BA5420081 outgoing
</code>```

Body:
I'm trying to connect to an RN42, module through python. When the RN42 pairs with W10 it creates two virtual COM ports(outgoing and incoming). I need to connect to the outgoing port.

I'm trying to do this automatically. I've tried:

import serial
import serial.tools.list_ports as port_lst

ports = list(port_lst.comports())
bluetooth_ports = []
for p in ports:
    if 'Bluetooth' in p.description:
        bluetooth_ports += [p.device]
bluetooth_com = serial.Serial(bluetooth_ports[0],115200)

I thought that the first port was usually the outgoing one, but I've paired the module to another computer, and this didn't apply (the second port was the outgoing one). Is there a way to find out the direction of the COM ports?

Thanks!!!

Body:
Although this is an antique question, I have been searching for the answer to this for some time myself and since I finally figured it out I wanted others to be able to find the answer. With help from a blog entry at in the hand and its accompanying gist:

The trick is to acquire the hwid using pySerial, then parse the address. The incoming port in a pair has an address of zero and the outgoing port has a nonzero address. Here is some ugly Python code that decodes it:

import serial.tools.list_ports
cp=serial.tools.list_ports.comports()
for p in cp:
    if "BTHENUM" in p.hwid:
        start_of_address=p.hwid.rfind("&")
        end_of_address=p.hwid.rfind("_")
        address=p.hwid[start_of_address+1:end_of_address]
        if int(address,16)==0:
            port_type="incoming"
        else:
            port_type="outgoing"
        print(p.hwid)
        print(p.name, address, port_type)

And the output:

BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\7&CC47540&0&000000000000_000000A8
COM4 000000000000 incoming
BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0002\7&CC47540&0&209BA5420081_C00000000
COM5 209BA5420081 outgoing


问:
how to display nested items using fetchData method in react.js
I'm able to fetch the data but not sure how to map nested items
data looks like that

```<code>{"id":3,
      "brands":[{"id":6,"products":[],
                 "title":"Lenovo",
                 "image":"/img.png",
                 "timestamp":"2022-02-07T15:11:36.059719+05:30",
                 "updated":"2022-02-07T15:11:36.059719+05:30",
                 "category":3}],
"title":"Laptop",
"image":"/img.png",
"timestamp":"2022-01-30T23:18:14.124583+05:30",
"updated":"2022-01-30T23:18:14.124583+05:30"}
</code>```

I'm using following method to do this.

```<code>const CategoriesToBrands = ({ match }) => {
  const [hasError, setErrors] = useState(false);
  const [items, setItems] = useState({});
  const { id } = useParams();
  async function fetchData() {
    const data  = await fetch("/api/v1/categories/nested/" + id);
    data.json()
      .then(data => setItems(data))
      .catch(data => setErrors(data));
  }
  useEffect(() => {
    fetchData()
  }, [])

  return (
    <div>
      <div>{JSON.stringify(items)}</div>
      <hr />
        {items.title}
      <hr />
      <div>Has error: {JSON.stringify(hasError)}</div>
    </div>
  );
};
export default CategoriesToBrands;
</code>```

I also tried multiple method suggested on stack overflow to map the items but no one seems to be working . or they are using another method . there can be multiple number of items in brands [] and i want to display each one of them for now there is one.. So what would be the syntax or method to map them properly.

答:
You have an brands array inside your main object fetched by async request. It means you should to get brands by items.brands. Something like that:

const CategoriesToBrands = ({ match }) => {
  const [hasError, setErrors] = useState(false);
  const [items, setItems] = useState({});
  const { id } = useParams();
  async function fetchData() {
    const data  = await fetch("/api/v1/categories/nested/" + id);
    data.json()
      .then(data => setItems(data))
      .catch(data => setErrors(data));
  }
  useEffect(() => {
    fetchData()
  }, [])

  return (

{JSON.stringify(items)}

        {items.title}

      {items.brands ? items.brands.map(brand => (

brand id: {brand.id}

      )) : null}

Has error: {JSON.stringify(hasError)}

  );
};
export default CategoriesToBrands;
```

The good idea is also changing the name of your const [items, setItems] = useState({});. In your case you are fetching one item, not multiple (I assume this fact by your id variable). So the name like item, setItem sounds better.

Body:
I'm able to fetch the data but not sure how to map nested items
data looks like that

{"id":3,
      "brands":[{"id":6,"products":[],
                 "title":"Lenovo",
                 "image":"/img.png",
                 "timestamp":"2022-02-07T15:11:36.059719+05:30",
                 "updated":"2022-02-07T15:11:36.059719+05:30",
                 "category":3}],
"title":"Laptop",
"image":"/img.png",
"timestamp":"2022-01-30T23:18:14.124583+05:30",
"updated":"2022-01-30T23:18:14.124583+05:30"}

I'm using following method to do this.

const CategoriesToBrands = ({ match }) => {
  const [hasError, setErrors] = useState(false);
  const [items, setItems] = useState({});
  const { id } = useParams();
  async function fetchData() {
    const data  = await fetch("/api/v1/categories/nested/" + id);
    data.json()
      .then(data => setItems(data))
      .catch(data => setErrors(data));
  }
  useEffect(() => {
    fetchData()
  }, [])

  return (

{JSON.stringify(items)}

        {items.title}

Has error: {JSON.stringify(hasError)}

  );
};
export default CategoriesToBrands;

I also tried multiple method suggested on stack overflow to map the items but no one seems to be working . or they are using another method . there can be multiple number of items in brands [] and i want to display each one of them for now there is one.. So what would be the syntax or method to map them properly.

Body:
You have an brands array inside your main object fetched by async request. It means you should to get brands by items.brands. Something like that:

const CategoriesToBrands = ({ match }) => {
  const [hasError, setErrors] = useState(false);
  const [items, setItems] = useState({});
  const { id } = useParams();
  async function fetchData() {
    const data  = await fetch("/api/v1/categories/nested/" + id);
    data.json()
      .then(data => setItems(data))
      .catch(data => setErrors(data));
  }
  useEffect(() => {
    fetchData()
  }, [])

  return (
    <div>
      <div>{JSON.stringify(items)}</div>
      <hr />
        {items.title}
      <hr />
      {items.brands ? items.brands.map(brand => (
         <div key={brand.id}>brand id: {brand.id}</div>
      )) : null}
      <div>Has error: {JSON.stringify(hasError)}</div>
    </div>
  );
};
export default CategoriesToBrands;

The good idea is also changing the name of your const [items, setItems] = useState({});. In your case you are fetching one item, not multiple (I assume this fact by your id variable). So the name like item, setItem sounds better.


问:
Using the JOIN function
I'm new to MySQL and am trying to learn more about the JOIN function.

Let's say I have the following code and I want to find the count for each level of
the variable and then join the two column.
So the data looks like:

```<code>in_clicks:
one
one
one
two
three
four
four
four
four
four
five
five
six
seven
seven
seven
eight
</code>```

and I'm trying to generate the following output:

```<code>four    5
one     3
seven   3
five    2
two     1
three   1
six     1
eight   1
</code>```

Not knowing anything about the JOIN function, I can use something similar to the following code to get my desired result. (it doesn't work)

```<code>SELECT(SELECT * FROM in_clicks) AS keys,
     (SELECT COUNT(*) FROM in_clicks) AS KeysNum;
</code>```

However, how can I use the JOIN function to optimize my sql code?

答:
You don't need a join here at all.  Assuming that number is the column you have listed:

```<code>SELECT number, COUNT(number)
FROM in_clicks
GROUP BY number
ORDER BY COUNT(number) DESC
</code>```

The COUNT() aggregate function basically counts the number of rows.  (COUNT(*) would have worked just as well.)  The magic here is GROUP BY number, which instructs the database to group the results by distinct values of number; the aggregate functions will evaluate each group separately.  Since there are five rows in the "four" group, COUNT() over that group will yield 5.

Selecting the number column is possible because we have grouped by it; without GROUP BY number we could not* select number alongside of an aggregate, since that wouldn't make sense.  Selecting this column allows you to see which group the corresponding aggregate result belongs to.

And the ORDER BY clause should be self-explanatory... sort the results descending by the count of rows in that group.  Note that the order of rows whose counts are the same is unspecified; you can do ORDER BY COUNT(number) DESC, number ASC if you want to order first by the count descending, then the number column ascending... but note that it will be a text comparison, so the order would be four, one, seven, five, eight, six, three, two.  If you order only by the count then the relative order of the one/seven and two/three/six/eight rows will not be reliable, since they have equal counts.

* Actually it is possible in MySQL to select non-aggregated columns that are not included in GROUP BY, but this is non-standard and should be used with utmost caution. Read more about it here.

Title: Using the JOIN function

Body:
I'm new to MySQL and am trying to learn more about the JOIN function.

Let's say I have the following code and I want to find the count for each level of
the variable and then join the two column.
So the data looks like:

in_clicks:
one
one
one
two
three
four
four
four
four
four
five
five
six
seven
seven
seven
eight

and I'm trying to generate the following output:

four    5
one     3
seven   3
five    2
two     1
three   1
six     1
eight   1

Not knowing anything about the JOIN function, I can use something similar to the following code to get my desired result. (it doesn't work)

SELECT(SELECT * FROM in_clicks) AS keys,
     (SELECT COUNT(*) FROM in_clicks) AS KeysNum;

However, how can I use the JOIN function to optimize my sql code?

Body:
You don't need a join here at all.  Assuming that number is the column you have listed:

SELECT number, COUNT(number)
FROM in_clicks
GROUP BY number
ORDER BY COUNT(number) DESC

The COUNT() aggregate function basically counts the number of rows.  (COUNT(*) would have worked just as well.)  The magic here is GROUP BY number, which instructs the database to group the results by distinct values of number; the aggregate functions will evaluate each group separately.  Since there are five rows in the "four" group, COUNT() over that group will yield 5.

Selecting the number column is possible because we have grouped by it; without GROUP BY number we could not* select number alongside of an aggregate, since that wouldn't make sense.  Selecting this column allows you to see which group the corresponding aggregate result belongs to.

And the ORDER BY clause should be self-explanatory... sort the results descending by the count of rows in that group.  Note that the order of rows whose counts are the same is unspecified; you can do ORDER BY COUNT(number) DESC, number ASC if you want to order first by the count descending, then the number column ascending... but note that it will be a text comparison, so the order would be four, one, seven, five, eight, six, three, two.  If you order only by the count then the relative order of the one/seven and two/three/six/eight rows will not be reliable, since they have equal counts.

* Actually it is possible in MySQL to select non-aggregated columns that are not included in GROUP BY, but this is non-standard and should be used with utmost caution. Read more about it here.


问:
multi-index df aggregation to nested dict
I'm trying to convert a multi-index df to a nested dictionary by aggregation sum of all index.

DataFrame is in the format

```<code>                    jan  feb
first second third
bar   bar1   bar3     0    5
             bar4     4    4
      bar2   bar5     1    9
foo   foo1   foo3     7    2
             foo4     7    7
      foo2   foo5     0    3

</code>```

I tried to aggregate with each index separately and convert to dict using .to_dict('records'). But couldn't able to achieve nested dictionary with aggregation of each index
expected result is

```<code>[
    {'first': 'bar',
     'jan': 5,
     'feb': 18,
     'sub_rows': [{'second': 'bar1',
                   'jan': 4,
                   'feb': 9,
                   'sub_rows': [{'third': 'bar3', 'jan': 0, 'feb': 5}, {'third': 'bar4', 'jan': 4, 'feb': 4}]
                   },
                  {'second': 'bar2',
                   'jan': 1,
                   'feb': 9,
                   'sub_rows': [{'third': 'bar5', 'jan': 1, 'feb': 9}]
                   }]
     },
    {'first': 'foo',
     'jan': 14,
     'feb': 12,
     'sub_rows': [{'second': 'foo1',
                   'jan': 14,
                   'feb': 9,
                   'sub_rows': [{'third': 'foo3', 'jan': 7, 'feb': 2}, {'third': 'foo4', 'jan': 7, 'feb': 7}]
                   },
                  {'second': 'foo2',
                   'jan': 0,
                   'feb': 3,
                   'sub_rows': [{'third': 'foo5', 'jan': 0, 'feb': 3}]
                   }]
     }
]
</code>```

Can you please guide me to achieve this format. Thanks

答:
Another recursive answer using a list as parameter:

```<code>def to_nested_dict(df, data=[]):
    lvl_name = df.index.get_level_values(0).name

    for name, subdf in df.groupby(level=0):
        d = {lvl_name: name} | subdf.sum().to_dict()
        data.append(d)
        if df.index.nlevels > 1:
            l = d.setdefault('sub_rows', [])
            to_nested_dict(subdf.loc[name], l)
    return data

data = to_nested_dict(df)
</code>```

Output:

```<code>>>> data
[{'first': 'bar',
  'jan': 5,
  'feb': 18,
  'sub_rows': [{'second': 'bar1',
    'jan': 4,
    'feb': 9,
    'sub_rows': [{'third': 'bar3', 'jan': 0, 'feb': 5},
     {'third': 'bar4', 'jan': 4, 'feb': 4}]},
   {'second': 'bar2',
    'jan': 1,
    'feb': 9,
    'sub_rows': [{'third': 'bar5', 'jan': 1, 'feb': 9}]}]},
 {'first': 'foo',
  'jan': 14,
  'feb': 12,
  'sub_rows': [{'second': 'foo1',
    'jan': 14,
    'feb': 9,
    'sub_rows': [{'third': 'foo3', 'jan': 7, 'feb': 2},
     {'third': 'foo4', 'jan': 7, 'feb': 7}]},
   {'second': 'foo2',
    'jan': 0,
    'feb': 3,
    'sub_rows': [{'third': 'foo5', 'jan': 0, 'feb': 3}]}]}]
</code>```

Body:
I'm trying to convert a multi-index df to a nested dictionary by aggregation sum of all index.

DataFrame is in the format

                    jan  feb
first second third
bar   bar1   bar3     0    5
             bar4     4    4
      bar2   bar5     1    9
foo   foo1   foo3     7    2
             foo4     7    7
      foo2   foo5     0    3

I tried to aggregate with each index separately and convert to dict using .to_dict('records'). But couldn't able to achieve nested dictionary with aggregation of each index
expected result is

[
    {'first': 'bar',
     'jan': 5,
     'feb': 18,
     'sub_rows': [{'second': 'bar1',
                   'jan': 4,
                   'feb': 9,
                   'sub_rows': [{'third': 'bar3', 'jan': 0, 'feb': 5}, {'third': 'bar4', 'jan': 4, 'feb': 4}]
                   },
                  {'second': 'bar2',
                   'jan': 1,
                   'feb': 9,
                   'sub_rows': [{'third': 'bar5', 'jan': 1, 'feb': 9}]
                   }]
     },
    {'first': 'foo',
     'jan': 14,
     'feb': 12,
     'sub_rows': [{'second': 'foo1',
                   'jan': 14,
                   'feb': 9,
                   'sub_rows': [{'third': 'foo3', 'jan': 7, 'feb': 2}, {'third': 'foo4', 'jan': 7, 'feb': 7}]
                   },
                  {'second': 'foo2',
                   'jan': 0,
                   'feb': 3,
                   'sub_rows': [{'third': 'foo5', 'jan': 0, 'feb': 3}]
                   }]
     }
]

Can you please guide me to achieve this format. Thanks

Body:
Another recursive answer using a list as parameter:

def to_nested_dict(df, data=[]):
    lvl_name = df.index.get_level_values(0).name

    for name, subdf in df.groupby(level=0):
        d = {lvl_name: name} | subdf.sum().to_dict()
        data.append(d)
        if df.index.nlevels > 1:
            l = d.setdefault('sub_rows', [])
            to_nested_dict(subdf.loc[name], l)
    return data

data = to_nested_dict(df)

Output:

>>> data
[{'first': 'bar',
  'jan': 5,
  'feb': 18,
  'sub_rows': [{'second': 'bar1',
    'jan': 4,
    'feb': 9,
    'sub_rows': [{'third': 'bar3', 'jan': 0, 'feb': 5},
     {'third': 'bar4', 'jan': 4, 'feb': 4}]},
   {'second': 'bar2',
    'jan': 1,
    'feb': 9,
    'sub_rows': [{'third': 'bar5', 'jan': 1, 'feb': 9}]}]},
 {'first': 'foo',
  'jan': 14,
  'feb': 12,
  'sub_rows': [{'second': 'foo1',
    'jan': 14,
    'feb': 9,
    'sub_rows': [{'third': 'foo3', 'jan': 7, 'feb': 2},
     {'third': 'foo4', 'jan': 7, 'feb': 7}]},
   {'second': 'foo2',
    'jan': 0,
    'feb': 3,
    'sub_rows': [{'third': 'foo5', 'jan': 0, 'feb': 3}]}]}]


问:
How to loop through a code only once then loop through other code over and over?
```<code>def urlCopy():
    py.moveTo(x=420,y=11,duration=2)
    py.click()
    #share
    py.moveTo(x=1054,y=946,duration=2)
    py.click()
    #copy
    py.moveTo(x=1175,y=630,duration=2)
    py.click()
    #1st tab
    py.moveTo(x=252,y=16,duration=2)
    py.click()
    py.moveTo(x=1093, y=517)
    py.click()
    if scrol == True:
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        varrs = py.hotkey('ctrl','v')
        global scrol
        scrol = False

    else:
        py.scroll(-300)
        py.tripleClick()
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        varrs = py.hotkey('ctrl','v')
</code>```

I am trying to copy youtube videos title and save it in other website.I want the code to run without scrolling at first loop and then always scrolling with next loops.I am going to loop this function again and again.

答:
You could use this:</p>
```<code>scrol = True
def urlCopy():
    global scrol #define scrol as global before you reference it
    py.moveTo(x=420,y=11,duration=2)
    py.click()
    #share
    py.moveTo(x=1054,y=946,duration=2)
    py.click()
    #copy
    py.moveTo(x=1175,y=630,duration=2)
    py.click()
    #1st tab
    py.moveTo(x=252,y=16,duration=2)
    py.click()
    py.moveTo(x=1093, y=517)
    py.click()
    if scrol == True: #referenced here
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        varrs = py.hotkey('ctrl','v')
        scrol = False

    else:
        py.scroll(-300)
        py.tripleClick()
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        varrs = py.hotkey('ctrl','v')
</code>```

Body:
def urlCopy():
    py.moveTo(x=420,y=11,duration=2)
    py.click()
    #share
    py.moveTo(x=1054,y=946,duration=2)
    py.click()
    #copy
    py.moveTo(x=1175,y=630,duration=2)
    py.click()
    #1st tab
    py.moveTo(x=252,y=16,duration=2)
    py.click()
    py.moveTo(x=1093, y=517)
    py.click()
    if scrol == True:
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        varrs = py.hotkey('ctrl','v')
        global scrol
        scrol = False

    else:
        py.scroll(-300)
        py.tripleClick()
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        varrs = py.hotkey('ctrl','v')

I am trying to copy youtube videos title and save it in other website.I want the code to run without scrolling at first loop and then always scrolling with next loops.I am going to loop this function again and again.

Body:
You could use this:

scrol = True
def urlCopy():
    global scrol #define scrol as global before you reference it
    py.moveTo(x=420,y=11,duration=2)
    py.click()
    #share
    py.moveTo(x=1054,y=946,duration=2)
    py.click()
    #copy
    py.moveTo(x=1175,y=630,duration=2)
    py.click()
    #1st tab
    py.moveTo(x=252,y=16,duration=2)
    py.click()
    py.moveTo(x=1093, y=517)
    py.click()
    if scrol == True: #referenced here
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        varrs = py.hotkey('ctrl','v')
        scrol = False

    else:
        py.scroll(-300)
        py.tripleClick()
        py.moveTo(x=154, y=420,duration=2)
        py.tripleClick()
        varrs = py.hotkey('ctrl','v')


问:
App is crashing when i click on any item in recyclerview
I was creating a recycler view and trying to create a toast when any item is clicked on using interface(i'm doing for first time). But my app is crashing when i click any item in recycler view.

Here is my main java file code.

```<code>package com.example.creatingrecyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements newsOnCkicked {
    RecyclerView r;
    String arr[]={"1","2","3","4","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        r=findViewById(R.id.rv);
        r.setLayoutManager(new LinearLayoutManager(this));
        CustomAdapter c=new CustomAdapter(arr,this);
        r.setAdapter(c);
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public String onItemClicked(String s) {
        Toast.makeText(this, "Item clicked is "+ s, Toast.LENGTH_SHORT).show();
        return null;
    }
}
</code>```

And this is my customadapter java code.

```<code>package com.example.creatingrecyclerview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;
    private newsOnCkicked k;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet,newsOnCkicked k) {
        localDataSet = dataSet;
        this.k=k;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);
        RecyclerView.ViewHolder v=new ViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View vi) {
                k.onItemClicked(localDataSet[v.getAdapterPosition()]);
            }
        });
        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}
interface newsOnCkicked extends View.OnClickListener {
    String onItemClicked(String s);
}
</code>```

Please help me find the error in the code. It will be great:)

答:
You have to set you click listener with viewHolder . copy the code below and paste then run

```<code>     public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;
    private newsOnCkicked k;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet,newsOnCkicked k) {
        localDataSet = dataSet;
        this.k=k;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);

        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View vi) {
                k.onItemClicked(localDataSet[viewHolder.getAdapterPosition()]);
            }
        });
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}
interface newsOnCkicked extends View.OnClickListener {
    String onItemClicked(String s);
}
</code>```

if still get problem comment below with error log.

Body:
I was creating a recycler view and trying to create a toast when any item is clicked on using interface(i'm doing for first time). But my app is crashing when i click any item in recycler view.

Here is my main java file code.

package com.example.creatingrecyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements newsOnCkicked {
    RecyclerView r;
    String arr[]={"1","2","3","4","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        r=findViewById(R.id.rv);
        r.setLayoutManager(new LinearLayoutManager(this));
        CustomAdapter c=new CustomAdapter(arr,this);
        r.setAdapter(c);
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public String onItemClicked(String s) {
        Toast.makeText(this, "Item clicked is "+ s, Toast.LENGTH_SHORT).show();
        return null;
    }
}

And this is my customadapter java code.

package com.example.creatingrecyclerview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;
    private newsOnCkicked k;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet,newsOnCkicked k) {
        localDataSet = dataSet;
        this.k=k;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);
        RecyclerView.ViewHolder v=new ViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View vi) {
                k.onItemClicked(localDataSet[v.getAdapterPosition()]);
            }
        });
        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}
interface newsOnCkicked extends View.OnClickListener {
    String onItemClicked(String s);
}

Please help me find the error in the code. It will be great:)

Body:
You have to set you click listener with viewHolder . copy the code below and paste then run

     public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;
    private newsOnCkicked k;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet,newsOnCkicked k) {
        localDataSet = dataSet;
        this.k=k;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);

        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View vi) {
                k.onItemClicked(localDataSet[viewHolder.getAdapterPosition()]);
            }
        });
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}
interface newsOnCkicked extends View.OnClickListener {
    String onItemClicked(String s);
}

if still get problem comment below with error log.


问:
Parsing out data from pytest assert and converting into a string
I want to collect data about test to an external database, where I would collect all assert and parse the expected value versus the actual result.

To describe what I want in code:

```<code>test_something.py:

def test_me_1(send_to_test):
    """
    Docstring to pad even more
    """
    x,y = send_to_test(3)
    assert x == 3**2
    assert y == 3**3
    assert y == 3**2 # I want this to fail intentionally

conftest.py:

@pytest.fixture(scope='function')
def send_to_test() -> Callable:
    return lambda x: (x ** 2, x ** 3)

</code>```

The data I want to collect is (Any other way is fine as long as I get this data):

```<code>test_data = [{'func': 'test_me_1', 'variable': 'x', 'expected_value': 9, 'actual_value': 9},
             {'func': 'test_me_1', 'variable': 'y', 'expected_value': 27, 'actual_value': 27},
             {'func': 'test_me_1', 'variable': 'y', 'expected_value': 27, 'actual_value': 9}]
</code>```

My current idea is a wrapper, that can easily be implemented to existing test and will collect the assert statements and their value.

Collecting the number of assert statements is straightforward if I use AST, but these are good only for static analysis.
I've also tried to use the inspect module, but have hard time figuring out how to use it for this purpose

My poor attempt thus far (print statements are temporary since I want to collect the data)

```<code>def get_this(func: Callable):
    @functools.wraps(func)
    def wrapper(*arg, **kwargs):
        print(func.__name__)
        func_content = inspect.getsource(func)
        func_root = ast.parse(func_content)
        for node in func_root.body:
            for content in node.body:
                if isinstance(content, ast.Assert):
                    print(content)
        return func(*arg, **kwargs)

    return wrapper
</code>```

答:
@hoefling answered my question with quite an easy solution of using the following hooks in conftest:

```<code>def pytest_assertrepr_compare(op, left, right):...
def pytest_assertion_pass(item, lineno, orig, expl):...
</code>```

According to the Pytest documentation, I have to add to pytest.ini enable_assertion_pass_hook=true and erase .pyc files, but other than that it works like a charm.
Now I have left and right comparisons with the operator used (pytest_assertrepr_compare) and if the test passed (pytest_assertion_pass).

Body:
I want to collect data about test to an external database, where I would collect all assert and parse the expected value versus the actual result.

To describe what I want in code:

test_something.py:

def test_me_1(send_to_test):
    """
    Docstring to pad even more
    """
    x,y = send_to_test(3)
    assert x == 3**2
    assert y == 3**3
    assert y == 3**2 # I want this to fail intentionally

conftest.py:

@pytest.fixture(scope='function')
def send_to_test() -> Callable:
    return lambda x: (x ** 2, x ** 3)

The data I want to collect is (Any other way is fine as long as I get this data):

test_data = [{'func': 'test_me_1', 'variable': 'x', 'expected_value': 9, 'actual_value': 9},
             {'func': 'test_me_1', 'variable': 'y', 'expected_value': 27, 'actual_value': 27},
             {'func': 'test_me_1', 'variable': 'y', 'expected_value': 27, 'actual_value': 9}]

My current idea is a wrapper, that can easily be implemented to existing test and will collect the assert statements and their value.

Collecting the number of assert statements is straightforward if I use AST, but these are good only for static analysis.
I've also tried to use the inspect module, but have hard time figuring out how to use it for this purpose

My poor attempt thus far (print statements are temporary since I want to collect the data)

def get_this(func: Callable):
    @functools.wraps(func)
    def wrapper(*arg, **kwargs):
        print(func.__name__)
        func_content = inspect.getsource(func)
        func_root = ast.parse(func_content)
        for node in func_root.body:
            for content in node.body:
                if isinstance(content, ast.Assert):
                    print(content)
        return func(*arg, **kwargs)

    return wrapper

Body:
@hoefling answered my question with quite an easy solution of using the following hooks in conftest:

def pytest_assertrepr_compare(op, left, right):...
def pytest_assertion_pass(item, lineno, orig, expl):...

According to the Pytest documentation, I have to add to pytest.ini enable_assertion_pass_hook=true and erase .pyc files, but other than that it works like a charm.
Now I have left and right comparisons with the operator used (pytest_assertrepr_compare) and if the test passed (pytest_assertion_pass).


问:
Android emulator won't shut down
The emulator starts up fine. But when you long-press the power button (or F7) and choose "Power off", it displays a "Shutting down" message which remains on-screen forever and the emulator won't actually shut down.

I can close the emulator window or kill its process. But I'm wondering if this is the correct way to shut down an Android emulator.

答:
AVD is running on port 5555, the easiest way to close it is using the below command line:

sudo lsof -n -i :5555

It will show the PID that is running your AVD, use -9 or -15 to kill the process

kill -9 [PID]

Title: Android emulator won't shut down


问:
Why do I get an authentication error when I pass an axios config object with an authorization token? MERN
I am making a small social network application. I came up with a like post route and the user has to be logged in to be able to perform that action, and I have auth middleware that looks like this:

```<code>const auth = async (req, res, next) => {
  // check header
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer')) {
    throw new UnauthenticatedError('Authentication invalid');
  }
  const token = authHeader.split(' ')[1];

  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET);

    req.user = { userId: payload.userId };
    next();
  } catch (error) {
    throw new UnauthenticatedError('Authentication invalid');
  }
};
</code>```

When I pass an object with an authorization token to Axios, I get an error, here is the action.js file:

```<code>export const likePost = id => async (dispatch, getState) => {
  try {
    const {
      userLogin: { userInfo },
    } = getState();

    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.token}`,
      },
    };

    const { data } = await axios.put(`/api/v1/post/${id}/like`, config);

    dispatch({ type: POST_LIKE_SUCCESS, payload: data });
  } catch (error) {
    console.log(error);
    dispatch({
      type: POST_LIKE_FAIL,
      payload: { msg: error.response.data.msg },
    });
  }
};
</code>```

When I open the network tab in the browser, the request tab shows that I forward the headers {Authorization: Bearer .... token} and in response I get error 401.

答:
I'm no expert with Axios, but according to the documentation, the put method uses data as the second argument and config as the third.

Maybe try to provide an empty value like null or an empty string for the second argument:

```<code>const { data } = await axios.put(`/api/v1/post/${id}/like`, null, config);
</code>```

Body:
I am making a small social network application. I came up with a like post route and the user has to be logged in to be able to perform that action, and I have auth middleware that looks like this:

const auth = async (req, res, next) => {
  // check header
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer')) {
    throw new UnauthenticatedError('Authentication invalid');
  }
  const token = authHeader.split(' ')[1];

  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET);

    req.user = { userId: payload.userId };
    next();
  } catch (error) {
    throw new UnauthenticatedError('Authentication invalid');
  }
};

When I pass an object with an authorization token to Axios, I get an error, here is the action.js file:

export const likePost = id => async (dispatch, getState) => {
  try {
    const {
      userLogin: { userInfo },
    } = getState();

    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.token}`,
      },
    };

    const { data } = await axios.put(`/api/v1/post/${id}/like`, config);

    dispatch({ type: POST_LIKE_SUCCESS, payload: data });
  } catch (error) {
    console.log(error);
    dispatch({
      type: POST_LIKE_FAIL,
      payload: { msg: error.response.data.msg },
    });
  }
};

When I open the network tab in the browser, the request tab shows that I forward the headers {Authorization: Bearer .... token} and in response I get error 401.

Body:
I'm no expert with Axios, but according to the documentation, the put method uses data as the second argument and config as the third.

Maybe try to provide an empty value like null or an empty string for the second argument:

const { data } = await axios.put(`/api/v1/post/${id}/like`, null, config);


问:
Check size of multiple uploaded files
I have a feature that allows users to upload multiple files. I want to check the size of these files and dissallow files that are too large

```<code>images = request.FILES['images'].size

if images > settings.MAX_UPLOAD_SIZE:
    raise Exception(f'Image {images} is too large 3mb max')
</code>```

I have been playing with this code but I cannot figure out a way to loop over all of the files.

What confuses me about this is i am not iterating over all the files but it still properly throws the exception no matter what order the file that is too large appears in.

Is this code working properly?

答:
You use .getlist(…) [Django-doc] to obtain the list of files:

```<code>for image in request.FILES<strong>.getlist('images')</strong>:
    if image.size > settings.MAX_UPLOAD_SIZE:
        raise Exception(f'Image {images} is too large 3mb max')</code>```

Title: Check size of multiple uploaded files

Body:
I have a feature that allows users to upload multiple files. I want to check the size of these files and dissallow files that are too large

images = request.FILES['images'].size

if images > settings.MAX_UPLOAD_SIZE:
    raise Exception(f'Image {images} is too large 3mb max')

I have been playing with this code but I cannot figure out a way to loop over all of the files.

What confuses me about this is i am not iterating over all the files but it still properly throws the exception no matter what order the file that is too large appears in.

Is this code working properly?

Body:
You use .getlist(…) [Django-doc] to obtain the list of files:

for image in request.FILES.getlist('images'):
    if image.size > settings.MAX_UPLOAD_SIZE:
        raise Exception(f'Image {images} is too large 3mb max')


问:
How to create a new column based off a number in an existing column that matches with another column's categorical value
I have a dataframe with game, category, if it's solo play or not, and with rating. I add a new column that contains the best game in terms of max rating in each category within each solo/double grouping.

```<code>category <- c("Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle")
solo <- c("solo","solo","solo","double","double","double","solo","solo","solo","double","double","double","solo","solo","solo","double","double","double")
game <- c("Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3")
rating <- c(8,7,6,5,3,3,2,1,10,3,4,5,6,3,2,1,3,1)
df <- as.data.frame(rating)
df$game <- game
df$solo <- solo
df$category <- category

df <- df  %>%
  group_by(category, solo) %>%
  mutate(best_game = max(rating, na.rm = TRUE)) %>%
  ungroup
</code>```

My question is, instead of having the highest rating (best_game) for each solo/double and category group, how can I add a column that has the game corresponding to the highest rating in best_game?

Example Output. Expected output is what I'd like to happen

```<code>rating    game    solo   category  best_game  **(expected_output)**
    5       Game1   double  Party   5            Game1
    3       Game1   double  Party   5            Game1
</code>```

答:
This works, but should be updated with what you want to do if more than one game has the max rating?

```<code>inner_join(
  df,
  df %>%
    group_by(category, solo) %>%
    filter(max(rating, na.rm = TRUE)==rating) %>%
    rename(best_game=game) %>%
    select(-rating),
  by=c("category","solo")
)
</code>```

Output

```<code>   rating  game   solo  category best_game
1       8 Game1   solo     Party     Game1
2       7 Game2   solo Adventure     Game2
3       6 Game3   solo    Puzzle     Game3
4       5 Game1 double     Party     Game1
5       3 Game2 double Adventure     Game2
6       3 Game3 double    Puzzle     Game3
7       2 Game1   solo     Party     Game1
8       1 Game2   solo Adventure     Game2
9      10 Game3   solo    Puzzle     Game3
10      3 Game1 double     Party     Game1
11      4 Game2 double Adventure     Game2
12      5 Game3 double    Puzzle     Game3
13      6 Game1   solo     Party     Game1
14      3 Game2   solo Adventure     Game2
15      2 Game3   solo    Puzzle     Game3
16      1 Game1 double     Party     Game1
17      3 Game2 double Adventure     Game2
18      1 Game3 double    Puzzle     Game3
</code>```

Body:
I have a dataframe with game, category, if it's solo play or not, and with rating. I add a new column that contains the best game in terms of max rating in each category within each solo/double grouping.

category <- c("Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle")
solo <- c("solo","solo","solo","double","double","double","solo","solo","solo","double","double","double","solo","solo","solo","double","double","double")
game <- c("Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3","Game1","Game2","Game3")
rating <- c(8,7,6,5,3,3,2,1,10,3,4,5,6,3,2,1,3,1)
df <- as.data.frame(rating)
df$game <- game
df$solo <- solo
df$category <- category

df <- df  %>%
  group_by(category, solo) %>%
  mutate(best_game = max(rating, na.rm = TRUE)) %>%
  ungroup

My question is, instead of having the highest rating (best_game) for each solo/double and category group, how can I add a column that has the game corresponding to the highest rating in best_game?

Example Output. Expected output is what I'd like to happen

rating    game    solo   category  best_game  **(expected_output)**
    5       Game1   double  Party   5            Game1
    3       Game1   double  Party   5            Game1

Body:
This works, but should be updated with what you want to do if more than one game has the max rating?

inner_join(
  df,
  df %>%
    group_by(category, solo) %>%
    filter(max(rating, na.rm = TRUE)==rating) %>%
    rename(best_game=game) %>%
    select(-rating),
  by=c("category","solo")
)

Output

   rating  game   solo  category best_game
1       8 Game1   solo     Party     Game1
2       7 Game2   solo Adventure     Game2
3       6 Game3   solo    Puzzle     Game3
4       5 Game1 double     Party     Game1
5       3 Game2 double Adventure     Game2
6       3 Game3 double    Puzzle     Game3
7       2 Game1   solo     Party     Game1
8       1 Game2   solo Adventure     Game2
9      10 Game3   solo    Puzzle     Game3
10      3 Game1 double     Party     Game1
11      4 Game2 double Adventure     Game2
12      5 Game3 double    Puzzle     Game3
13      6 Game1   solo     Party     Game1
14      3 Game2   solo Adventure     Game2
15      2 Game3   solo    Puzzle     Game3
16      1 Game1 double     Party     Game1
17      3 Game2 double Adventure     Game2
18      1 Game3 double    Puzzle     Game3