问:
How To Scale The Contents Of A UIView To Fit A Destination Rectangle Whilst Maintaining The Aspect Ratio?
I am trying to solve a problem without success and am hoping someone could help.

I have looked for similar posts but haven't been able to find anything which solves my problem.

My Scenario is as follows:
I have a UIView on which a number of other UIViews can be placed. These can be moved, scaled and rotated using gesture recognisers (There is no issue here).
The User is able to change the Aspect Ratio of the Main View (the Canvas) and my problem is trying to scale the content of the Canvas to fit into the new destination size.

There are a number of posts with a similar theme e.g:

calculate new size and location on a CGRect

How to create an image of specific size from UIView

But these don't address the changing of ratios multiple times.

My Approach:

When I change the aspect ratio of the canvas, I make use of AVFoundation to calculate an aspect fitted rectangle which the subviews of the canvas should fit:

```<code>let sourceRectangleSize = canvas.frame.size

canvas.setAspect(aspect, screenSize: editorLayoutGuide.layoutFrame.size)
view.layoutIfNeeded()

let destinationRectangleSize = canvas.frame.size

let aspectFittedFrame = AVMakeRect(aspectRatio:sourceRectangleSize, insideRect: CGRect(origin: .zero, size: destinationRectangleSize))
ratioVisualizer.frame = aspectFittedFrame
</code>```

The Red frame is simply to visualise the Aspect Fitted Rectangle. As you can see whilst the aspect fitted rectangle is correct, the scaling of objects isn't working. This is especially true when I apply scale and rotation to the subviews (CanvasElement).

The logic where I am scaling the objects is clearly wrong:

```<code>@objc
private func setRatio(_ control: UISegmentedControl) {
  guard let aspect = Aspect(rawValue: control.selectedSegmentIndex) else { return }

  let sourceRectangleSize = canvas.frame.size

  canvas.setAspect(aspect, screenSize: editorLayoutGuide.layoutFrame.size)
  view.layoutIfNeeded()

  let destinationRectangleSize = canvas.frame.size

  let aspectFittedFrame = AVMakeRect(aspectRatio:sourceRectangleSize, insideRect: CGRect(origin: .zero, size: destinationRectangleSize))
  ratioVisualizer.frame = aspectFittedFrame

  let scale = min(aspectFittedFrame.size.width/canvas.frame.width, aspectFittedFrame.size.height/canvas.frame.height)

  for case let canvasElement as CanvasElement in canvas.subviews {

    canvasElement.frame.size = CGSize(
      width: canvasElement.baseFrame.width * scale,
      height: canvasElement.baseFrame.height * scale
    )
    canvasElement.frame.origin = CGPoint(
      x: aspectFittedFrame.origin.x + canvasElement.baseFrame.origin.x * scale,
      y:  aspectFittedFrame.origin.y + canvasElement.baseFrame.origin.y * scale
    )
  }
}
</code>```

I am enclosing the CanvasElement Class as well if this helps:

```<code>final class CanvasElement: UIView {

  var rotation: CGFloat = 0
  var baseFrame: CGRect = .zero

  var id: String = UUID().uuidString

  // MARK: - Initialization

  override init(frame: CGRect) {
    super.init(frame: frame)
    storeState()
    setupGesture()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }

  // MARK: - Gesture Setup

  private func setupGesture() {
    let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGesture(_:)))
    let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchGesture(_:)))
    let rotateGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(rotateGesture(_:)))
    addGestureRecognizer(panGestureRecognizer)
    addGestureRecognizer(pinchGestureRecognizer)
    addGestureRecognizer(rotateGestureRecognizer)
  }

  // MARK: - Touches

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    moveToFront()
  }

  //MARK: - Gestures

  @objc
  private func panGesture(_ sender: UIPanGestureRecognizer) {
    let move = sender.translation(in: self)
    transform = transform.concatenating(.init(translationX: move.x, y: move.y))
    sender.setTranslation(CGPoint.zero, in: self)
    storeState()
  }

  @objc
  private func pinchGesture(_ sender: UIPinchGestureRecognizer) {
    transform = transform.scaledBy(x: sender.scale, y: sender.scale)
    sender.scale = 1
    storeState()
  }

  @objc
  private func rotateGesture(_ sender: UIRotationGestureRecognizer) {
    rotation += sender.rotation
    transform = transform.rotated(by: sender.rotation)
    sender.rotation = 0
    storeState()
  }

  // MARK: - Miscelaneous

  func moveToFront() {
    superview?.bringSubviewToFront(self)
  }

  public func rotated(by degrees: CGFloat) {
    transform = transform.rotated(by: degrees)
    rotation += degrees
  }

  func storeState() {
    print("""
    Element Frame = \(frame)
    Element Bounds = \(bounds)
    Element Center = \(center)
    """)
    baseFrame = frame
  }
}
</code>```

Any help or advise, approaches, with some actual examples would be great. Im not expecting anyone to provide full source code, but something which I could use as a basis.

Thank you for taking the time to read my question.

答:
Maybe you can make the three rectangles in a view. And then you can keep the  aspect-ratio for the view.

If you are using autolayout and Snapkit. The constrains maybe like this:

```<code>view.snp.makeConstraints { make in
  make.width.height.lessThanOrEqualToSuperview()
  make.centerX.centerY.equalToSuperview()
  make.width.equalTo(view.snp.height)
  make.width.height.equalToSuperview().priority(.high)
}
</code>```

So this view will be aspect-fit in superview.

Back to children in this view. If you want to scale every child when view's frame changed, you should add contrains too. Or you can use autoresizingMask, it maybe simpler.

If you didn't want to use autolayout. Maybe you can try transform. When you transform some view, the children in this view will be changed too.

```<code>// The scale depends on the aspect-ratio of superview.
view.transform = CGAffineTransformMakeScale(0.5, 0.5);
</code>```

Body:
I am trying to solve a problem without success and am hoping someone could help.

I have looked for similar posts but haven't been able to find anything which solves my problem.

My Scenario is as follows:
I have a UIView on which a number of other UIViews can be placed. These can be moved, scaled and rotated using gesture recognisers (There is no issue here).
The User is able to change the Aspect Ratio of the Main View (the Canvas) and my problem is trying to scale the content of the Canvas to fit into the new destination size.

There are a number of posts with a similar theme e.g:

calculate new size and location on a CGRect

How to create an image of specific size from UIView

But these don't address the changing of ratios multiple times.

My Approach:

When I change the aspect ratio of the canvas, I make use of AVFoundation to calculate an aspect fitted rectangle which the subviews of the canvas should fit:

let sourceRectangleSize = canvas.frame.size

canvas.setAspect(aspect, screenSize: editorLayoutGuide.layoutFrame.size)
view.layoutIfNeeded()

let destinationRectangleSize = canvas.frame.size

let aspectFittedFrame = AVMakeRect(aspectRatio:sourceRectangleSize, insideRect: CGRect(origin: .zero, size: destinationRectangleSize))
ratioVisualizer.frame = aspectFittedFrame

The Red frame is simply to visualise the Aspect Fitted Rectangle. As you can see whilst the aspect fitted rectangle is correct, the scaling of objects isn't working. This is especially true when I apply scale and rotation to the subviews (CanvasElement).

The logic where I am scaling the objects is clearly wrong:

@objc
private func setRatio(_ control: UISegmentedControl) {
  guard let aspect = Aspect(rawValue: control.selectedSegmentIndex) else { return }

  let sourceRectangleSize = canvas.frame.size

  canvas.setAspect(aspect, screenSize: editorLayoutGuide.layoutFrame.size)
  view.layoutIfNeeded()

  let destinationRectangleSize = canvas.frame.size

  let aspectFittedFrame = AVMakeRect(aspectRatio:sourceRectangleSize, insideRect: CGRect(origin: .zero, size: destinationRectangleSize))
  ratioVisualizer.frame = aspectFittedFrame

  let scale = min(aspectFittedFrame.size.width/canvas.frame.width, aspectFittedFrame.size.height/canvas.frame.height)

  for case let canvasElement as CanvasElement in canvas.subviews {

    canvasElement.frame.size = CGSize(
      width: canvasElement.baseFrame.width * scale,
      height: canvasElement.baseFrame.height * scale
    )
    canvasElement.frame.origin = CGPoint(
      x: aspectFittedFrame.origin.x + canvasElement.baseFrame.origin.x * scale,
      y:  aspectFittedFrame.origin.y + canvasElement.baseFrame.origin.y * scale
    )
  }
}

I am enclosing the CanvasElement Class as well if this helps:

final class CanvasElement: UIView {

  var rotation: CGFloat = 0
  var baseFrame: CGRect = .zero

  var id: String = UUID().uuidString

  // MARK: - Initialization

  override init(frame: CGRect) {
    super.init(frame: frame)
    storeState()
    setupGesture()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }

  // MARK: - Gesture Setup

  private func setupGesture() {
    let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGesture(_:)))
    let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchGesture(_:)))
    let rotateGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(rotateGesture(_:)))
    addGestureRecognizer(panGestureRecognizer)
    addGestureRecognizer(pinchGestureRecognizer)
    addGestureRecognizer(rotateGestureRecognizer)
  }

  // MARK: - Touches

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    moveToFront()
  }

  //MARK: - Gestures

  @objc
  private func panGesture(_ sender: UIPanGestureRecognizer) {
    let move = sender.translation(in: self)
    transform = transform.concatenating(.init(translationX: move.x, y: move.y))
    sender.setTranslation(CGPoint.zero, in: self)
    storeState()
  }

  @objc
  private func pinchGesture(_ sender: UIPinchGestureRecognizer) {
    transform = transform.scaledBy(x: sender.scale, y: sender.scale)
    sender.scale = 1
    storeState()
  }

  @objc
  private func rotateGesture(_ sender: UIRotationGestureRecognizer) {
    rotation += sender.rotation
    transform = transform.rotated(by: sender.rotation)
    sender.rotation = 0
    storeState()
  }

  // MARK: - Miscelaneous

  func moveToFront() {
    superview?.bringSubviewToFront(self)
  }

  public func rotated(by degrees: CGFloat) {
    transform = transform.rotated(by: degrees)
    rotation += degrees
  }

  func storeState() {
    print("""
    Element Frame = \(frame)
    Element Bounds = \(bounds)
    Element Center = \(center)
    """)
    baseFrame = frame
  }
}

Any help or advise, approaches, with some actual examples would be great. Im not expecting anyone to provide full source code, but something which I could use as a basis.

Thank you for taking the time to read my question.

Body:
Maybe you can make the three rectangles in a view. And then you can keep the  aspect-ratio for the view.

If you are using autolayout and Snapkit. The constrains maybe like this:

view.snp.makeConstraints { make in
  make.width.height.lessThanOrEqualToSuperview()
  make.centerX.centerY.equalToSuperview()
  make.width.equalTo(view.snp.height)
  make.width.height.equalToSuperview().priority(.high)
}

So this view will be aspect-fit in superview.

Back to children in this view. If you want to scale every child when view's frame changed, you should add contrains too. Or you can use autoresizingMask, it maybe simpler.

If you didn't want to use autolayout. Maybe you can try transform. When you transform some view, the children in this view will be changed too.

// The scale depends on the aspect-ratio of superview.
view.transform = CGAffineTransformMakeScale(0.5, 0.5);


来源: stackexchange

问:
Would giving a list of objects to another class , not make this relation aggregation?
```<code>class A:
    def __init__(self, id, name ,age):
        self.id = id
        self.name = name
        self.age = age

    def get_id(self):
        return self.id

    def get_name(self):
        return self.name

    def get_age(self):
        return self.age

class B:
    def __init__(self, lst, file):
        self.lst = lst
        self.file = file

    def writefile(self):
        fileObj = open(self.file, 'w')
        write_string = ''
        for person in self.lst:
            for func in [person.get_id, person.get_name, person.get_age]:
                write_string += func() + '\t'
            write_string = write_string[:-1] + '\n'
        fileObj.write(write_string[:-1])
        fileObj.close()

def main():
    file = 'sample.txt'

    def loadfile():
        try:
            filez = open(file, 'r')
        except FileNotFoundError:
            filez = open(file, 'w')
            filez.close()
            filez = open(file, 'r')
        lst = []
        for line in filez:
            id, name, age = line.split('\t')
            age = date.rstrip('\n')
            lst.append(A(id, name, age))
        return lst

    population = loadfile()
    call = B(population, file)

    def add():
        obj_A1 = A('1','bilal','29')
        obj_A3 = A('3','asda','54')
        population.append(obj_A1)
        population.append(obj_A3)
    add()

    def display():
        for i in population:
            if i.get_id() == '3':
                print('found')
    display()

    call.writefile()

main()
</code>```

Im new to OOP. im trying to understand if giving a list of objects to class B would make any difference to its relation. The relation i hope here is aggregation between Class A and class B if im not wrong since im adding population list to class B ? ps. sorry for the long code.

答:
According to Martin Fowler's UML Distilled:

Aggregation is strictly meaningless; as a result, I recommend that you ignore it in your own diagrams.

That leaves us with the question of whether the objects contained within lst have an association or composition relationship with B?

Composition implies that the objects being composed do not outlive their container classes. It also implies that they are not shared by other container classes.

Association defines a looser coupling relationship than composition, namely that one object merely refers to another object. In python this basically translates to the idea that the class has a certain instance attribute.

In your code you first instantiate population then pass it to B's constructor. Suppose you had another object C which could take in a list object just like B:

class C:
    def __init__(self, lst, file):
        self.lst = lst
        self.file = file
```
<p>One could imagine that later in your <code>main</code> block, the <code>population</code> variable could be reused to instantiate <code>C</code>. This would result in a shared instance attribute between <code>B</code> and <code>C</code>. Also if you called <code>del B</code> somewhere later in your code, it wouldn't destroy <code>population</code>. You therefore have a mere <strong>association</strong> relationship here.</p>
<p>If you wanted to implement true composition (which I assume is what you mean by aggregation), you could either instantiate the list within your constructor:</p>
<pre class="lang-py prettyprint-override"><code>class B:
    def __init__(self, file):
        self.lst = loadfile(file)
        self.file = file
</code>```

Or you could instantiate the list upon B instantiation as follows:

call = B(loadfile(file), file)
```

ContentLicense: CC BY-SA 4.0

Body:
class A:
    def __init__(self, id, name ,age):
        self.id = id
        self.name = name
        self.age = age

    def get_id(self):
        return self.id

    def get_name(self):
        return self.name

    def get_age(self):
        return self.age

class B:
    def __init__(self, lst, file):
        self.lst = lst
        self.file = file

    def writefile(self):
        fileObj = open(self.file, 'w')
        write_string = ''
        for person in self.lst:
            for func in [person.get_id, person.get_name, person.get_age]:
                write_string += func() + '\t'
            write_string = write_string[:-1] + '\n'
        fileObj.write(write_string[:-1])
        fileObj.close()

def main():
    file = 'sample.txt'

    def loadfile():
        try:
            filez = open(file, 'r')
        except FileNotFoundError:
            filez = open(file, 'w')
            filez.close()
            filez = open(file, 'r')
        lst = []
        for line in filez:
            id, name, age = line.split('\t')
            age = date.rstrip('\n')
            lst.append(A(id, name, age))
        return lst

    population = loadfile()
    call = B(population, file)

    def add():
        obj_A1 = A('1','bilal','29')
        obj_A3 = A('3','asda','54')
        population.append(obj_A1)
        population.append(obj_A3)
    add()

    def display():
        for i in population:
            if i.get_id() == '3':
                print('found')
    display()

    call.writefile()

main()

Im new to OOP. im trying to understand if giving a list of objects to class B would make any difference to its relation. The relation i hope here is aggregation between Class A and class B if im not wrong since im adding population list to class B ? ps. sorry for the long code.

Body:
According to Martin Fowler's UML Distilled:

Aggregation is strictly meaningless; as a result, I recommend that you ignore it in your own diagrams.

That leaves us with the question of whether the objects contained within lst have an association or composition relationship with B?

Composition implies that the objects being composed do not outlive their container classes. It also implies that they are not shared by other container classes.

Association defines a looser coupling relationship than composition, namely that one object merely refers to another object. In python this basically translates to the idea that the class has a certain instance attribute.

In your code you first instantiate population then pass it to B's constructor. Suppose you had another object C which could take in a list object just like B:

class C:
    def __init__(self, lst, file):
        self.lst = lst
        self.file = file

One could imagine that later in your main block, the population variable could be reused to instantiate C. This would result in a shared instance attribute between B and C. Also if you called del B somewhere later in your code, it wouldn't destroy population. You therefore have a mere association relationship here.

If you wanted to implement true composition (which I assume is what you mean by aggregation), you could either instantiate the list within your constructor:

class B:
    def __init__(self, file):
        self.lst = loadfile(file)
        self.file = file

Or you could instantiate the list upon B instantiation as follows:

call = B(loadfile(file), file)


问:
How can I configure my event bus in ASP.NET Core 6 - Migration to .NET 6
I want to migrate from ASP.NET Core 5 to ASP.NET Core 6. How can I configure by event bus in .NET 6?

Here is my code in ASP.NET Core 5:

IEventBus.cs class

```<code>public interface IEventBus
{
    void Publish<TEvent>(TEvent @event)
        where TEvent : Event;

    void Subscribe<TEvent, TEventHandler>()
        where TEvent : Event
        where TEventHandler : IEventHandler<TEvent>;

    void Unsubscribe<TEvent, TEventHandler>()
        where TEvent : Event
        where TEventHandler : IEventHandler<TEvent>;
}
</code>```

Startup.cs class

```<code>private void ConfigureEventBusHandlers(IApplicationBuilder app)
{
    var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
    eventBus.Subscribe<MessageSentEvent, MessageSentEventHandler>();
}
</code>```

The code works on ASP.NET Core 5. But in .NET 6, I encounter an error.

Here is my code in ASP.NET Core 6:

```<code>var app = builder.Build();

var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<MessageSentEvent, MessageSentEventHandler>();
</code>```

And here is the error:

WebApplication does not contain a definition for 'ApplicationServices'

I could not inject IApplicationBuilder either.

答:
In Program.cs try this code:

```<code>var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IEventBus,EventBus>();

ServiceProvider serviceProvider = builder.Services.BuildServiceProvider();
var eventBus = serviceProvider.GetRequiredService<IEventBus>();
eventBus.Subscribe<MessageSentEvent, MessageSentEventHandler>();
</code>```

Body:
I want to migrate from ASP.NET Core 5 to ASP.NET Core 6. How can I configure by event bus in .NET 6?

Here is my code in ASP.NET Core 5:

IEventBus.cs class

public interface IEventBus
{
    void Publish<TEvent>(TEvent @event)
        where TEvent : Event;

    void Subscribe<TEvent, TEventHandler>()
        where TEvent : Event
        where TEventHandler : IEventHandler<TEvent>;

    void Unsubscribe<TEvent, TEventHandler>()
        where TEvent : Event
        where TEventHandler : IEventHandler<TEvent>;
}

Startup.cs class

private void ConfigureEventBusHandlers(IApplicationBuilder app)
{
    var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
    eventBus.Subscribe<MessageSentEvent, MessageSentEventHandler>();
}

The code works on ASP.NET Core 5. But in .NET 6, I encounter an error.

Here is my code in ASP.NET Core 6:

var app = builder.Build();

var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<MessageSentEvent, MessageSentEventHandler>();

And here is the error:

WebApplication does not contain a definition for 'ApplicationServices'

I could not inject IApplicationBuilder either.

Body:
In Program.cs try this code:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IEventBus,EventBus>();

ServiceProvider serviceProvider = builder.Services.BuildServiceProvider();
var eventBus = serviceProvider.GetRequiredService<IEventBus>();
eventBus.Subscribe<MessageSentEvent, MessageSentEventHandler>();


问:
Finding if there is a space in a list(return boolean value)
Looking for some help on a tick tac toe exercise:

I have the bellow:

test_board = ['#','X','O','X','O','X','O','','O','X']

```<code>def space_check(board,position):
    free_space = ""
    if free_space in board[position]:
        return True
    else:
        return False
</code>```

When running the function I cannot see the False return, only True:

```<code>space_check(test_board,7)
Output: True
space_check(test_board,9)
Output: True
</code>```

答:
Change your function with this:</p>
```<code>def space_check(board,position):
    free_space = ""
    return free_space == board[position]

test_board = ['#','X','O','X','O','X','O','','O','X']
space_check(test_board, 7)
Output : True

space_check(test_board, 9)
Output: False
</code>```

Body:
Looking for some help on a tick tac toe exercise:

I have the bellow:

test_board = ['#','X','O','X','O','X','O','','O','X']

def space_check(board,position):
    free_space = ""
    if free_space in board[position]:
        return True
    else:
        return False

When running the function I cannot see the False return, only True:

space_check(test_board,7)
Output: True
space_check(test_board,9)
Output: True

Body:
Change your function with this:

def space_check(board,position):
    free_space = ""
    return free_space == board[position]

test_board = ['#','X','O','X','O','X','O','','O','X']
space_check(test_board, 7)
Output : True

space_check(test_board, 9)
Output: False


问:
data access problem in jsf
I have the following class-files:

```<code>class RowData {
...
  ArrayList<String> valueMap;
...
}

class Bean {
...
  public List<RowData> getData() {
  ...
  }
}
</code>```

jsf code snippet:

```<code>...
<h:form>
  <rich:dataTable id="overviewTable" value="#{bean.getData()}" var="row">

    <c:forEach items="#{row.valueMap}" var="r">

      <rich:column>
        <h:outputText value="#{r}" />
      </rich:column>
    </c:forEach>
  </rich:dataTable>
</h:form>
...
</code>```

Unfortunately, the table doesn't appear. What's wrong? The page doesn't show an error or something, the table is just not there (in this version I skipped all the getter and setter...). When I want to access other data from the bean, it works, so the whole setup should be ok.

答:
Use value="#{bean.data}" instead. Remember, you're using E.L and it is assumed that you're referencing a java bean property named data through the getter method getData(). The data property might not exists but the method named should definitely be named like this.

Also, in order to use the items="#{row.valueMap}" idiom, you must have a getValueMap() method present in your bean class.

Do you get the idea?

ContentLicense: CC BY-SA 3.0

Title: data access problem in jsf

Body:
I have the following class-files:

class RowData {
...
  ArrayList<String> valueMap;
...
}

class Bean {
...
  public List<RowData> getData() {
  ...
  }
}

jsf code snippet:

...
<h:form>
  <rich:dataTable id="overviewTable" value="#{bean.getData()}" var="row">

    <c:forEach items="#{row.valueMap}" var="r">

      <rich:column>
        <h:outputText value="#{r}" />
      </rich:column>
    </c:forEach>
  </rich:dataTable>
</h:form>
...

Unfortunately, the table doesn't appear. What's wrong? The page doesn't show an error or something, the table is just not there (in this version I skipped all the getter and setter...). When I want to access other data from the bean, it works, so the whole setup should be ok.


问:
React Native - Fetch Problem: TypeError: NetworkError when attempting to fetch resource. ‘Access-Control-Allow-Origin’
I have a problem. I call/request url in this code;

```<code>fetch("http://url",{
method:'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
.then(res=>
console.log(res)
)
.catch(error => console.log(error))
</code>```

But i get the error:
TypeError: NetworkError when attempting to fetch resource.
And i am checking console network then i see CORS failed.

Can you help me ?

Thank you

答:
I fixed it. If I call/request with an android device, it's not a problem.
But if I call/request with the web, that's time get the error.
That's why I am not using a web interface.

An edit of my code:

```<code>fetch("http://url",{
          method:'GET',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
          }
        })
        .then(res=> res.json())
        .then(res=>{
          console.log("ImageUrl: ", res);
        })
        .catch(error => console.log(error))
</code>```

Body:
I have a problem. I call/request url in this code;

fetch("http://url",{
method:'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
.then(res=>
console.log(res)
)
.catch(error => console.log(error))

But i get the error:
TypeError: NetworkError when attempting to fetch resource.
And i am checking console network then i see CORS failed.

Can you help me ?

Thank you

Body:
I fixed it. If I call/request with an android device, it's not a problem.
But if I call/request with the web, that's time get the error.
That's why I am not using a web interface.

An edit of my code:

fetch("http://url",{
          method:'GET',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
          }
        })
        .then(res=> res.json())
        .then(res=>{
          console.log("ImageUrl: ", res);
        })
        .catch(error => console.log(error))


问:
How do I fix other data not adding to previous data in react infinite scroll?
This my first time implementing react infinite scrolling. I ran into difficulty where the initial array of data keep repeating.

```<code>function Details() {
const [facility, setFacility] = useState([]);
  const [loading, setLoading] = useState(true);

  const getFacility = useCallback(async () => {
    let skip = 0;
    setLoading(true)
    await Axios.get(
      `...apiUrl/${wardTitle}/ward/details?limit=${10}&skip=${skip}`
    ).then((response) => {
      const details = response.data.data;
      setFacility((prev) => [...prev, ...details]);
      setLoading(false)
    });

  }, [wardTitle]);

  const handleScroll =  (e) => {
    const { scrollTop, scrollHeight, clientHeight} = e.currentTarget;

    if(clientHeight + scrollTop + 1 >= scrollHeight ){
      getFacility();
    }
  };

  useEffect(() => {
    getFacility();

  }, [getFacility]);

return (
<>
  {facility.map((cur) => (
  <div>{curr}</div>
 {loading && <h4>Loading ...</h4>
)
</>
)

}
</code>```

Everything seems fine other than the data repetition. I dont know where i got it wrong in the call. I would appreciate any help.

答:
i can see so many errors in your code check the spellings too.
You are not explaining what you really want to do?
infinite scrolling like facebook?</p>

Body:
This my first time implementing react infinite scrolling. I ran into difficulty where the initial array of data keep repeating.

function Details() {
const [facility, setFacility] = useState([]);
  const [loading, setLoading] = useState(true);

  const getFacility = useCallback(async () => {
    let skip = 0;
    setLoading(true)
    await Axios.get(
      `...apiUrl/${wardTitle}/ward/details?limit=${10}&skip=${skip}`
    ).then((response) => {
      const details = response.data.data;
      setFacility((prev) => [...prev, ...details]);
      setLoading(false)
    });

  }, [wardTitle]);

  const handleScroll =  (e) => {
    const { scrollTop, scrollHeight, clientHeight} = e.currentTarget;

    if(clientHeight + scrollTop + 1 >= scrollHeight ){
      getFacility();
    }
  };

  useEffect(() => {
    getFacility();

  }, [getFacility]);

return (
<>
  {facility.map((cur) => (

{curr}

 {loading &&
Loading ...

)
</>
)

}

Everything seems fine other than the data repetition. I dont know where i got it wrong in the call. I would appreciate any help.


问:
How to automatically update R to the latest patched version?
Is there any way to automatically update R on Mac OS X to the latest patched version (R-Patched) on a daily basis or some predetermined intervals?</p>

答:
I have a bash script that installs the daily patched build from http://r.research.att.com. Installed libraries remain untouched, except for those in core.

I update manually, but you could set up a cron job as @bnaul suggests. I'm not sure how it will handle the need for sudo'ing, however. You might have to move your R out of /Library/Frameworks and then change the script accordingly.

```<code>#!/bin/bash
curl -s http://r.research.att.com/R-2.13-branch-leopard-universal.tar.gz | sudo tar fvxz - -C /
</code>```

Body:
I have a bash script that installs the daily patched build from http://r.research.att.com. Installed libraries remain untouched, except for those in core.

I update manually, but you could set up a cron job as @bnaul suggests. I'm not sure how it will handle the need for sudo'ing, however. You might have to move your R out of /Library/Frameworks and then change the script accordingly.

#!/bin/bash
curl -s http://r.research.att.com/R-2.13-branch-leopard-universal.tar.gz | sudo tar fvxz - -C /


问:
How to Move bottomsheet along with keyboard which has textfield(autofocused is true)?
I'm trying to make a bottomsheet that has a text field and autofocus is set to true so that the keyboard pops up. But, bottomsheet is overlapped by the keyboard. Is there a way to move bottomsheet above the keyboard?</p>
```<code>Padding(
  padding:
      EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
  child: Column(children: <Widget>[
    TextField(
      autofocus: true,
      decoration: InputDecoration(hintText: 'Title'),
    ),
    TextField(
      decoration: InputDecoration(hintText: 'Details!'),
      keyboardType: TextInputType.multiline,
      maxLines: 4,
    ),
    TextField(
      decoration: InputDecoration(hintText: 'Additional details!'),
      keyboardType: TextInputType.multiline,
      maxLines: 4,
    ),]);
</code>```

答:
If you still have not found your issue. So I think you have missed in your BuilderContext. Sometimes when you implement modalBottomSheet it will give you only the context parameter. So add context with BuildContext.

```<code> builder: (BuildContext context) {  //-Here is your issue add BuilderContext class name as it as
          return Padding(
            padding: MediaQuery.of(context).viewInsets,
            child: SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                child: new Container(
</code>```

Body:
I'm trying to make a bottomsheet that has a text field and autofocus is set to true so that the keyboard pops up. But, bottomsheet is overlapped by the keyboard. Is there a way to move bottomsheet above the keyboard?

Padding(
  padding:
      EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
  child: Column(children: <Widget>[
    TextField(
      autofocus: true,
      decoration: InputDecoration(hintText: 'Title'),
    ),
    TextField(
      decoration: InputDecoration(hintText: 'Details!'),
      keyboardType: TextInputType.multiline,
      maxLines: 4,
    ),
    TextField(
      decoration: InputDecoration(hintText: 'Additional details!'),
      keyboardType: TextInputType.multiline,
      maxLines: 4,
    ),]);

Body:
If you still have not found your issue. So I think you have missed in your BuilderContext. Sometimes when you implement modalBottomSheet it will give you only the context parameter. So add context with BuildContext.

 builder: (BuildContext context) {  //-Here is your issue add BuilderContext class name as it as
          return Padding(
            padding: MediaQuery.of(context).viewInsets,
            child: SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                child: new Container(


问:
TestNG by default disables loading DTD from unsecure Urls
I'm using testng maven and selenium to run my tests, currently I have the following testng.xml file

Looks like the problem is with the &listeners and &classes lines, If I replace those lines with the xml content that I have on the referenced files it runs fine. I have used this in a previous project and it worked fine, not sure why I'm getting this error.

```<code><?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"   [
        <!ENTITY listeners SYSTEM "listeners.xml">
        <!ENTITY classes SYSTEM "classes.xml">
        ]>
<suite name="Local Execution" verbose="5">
    &listeners;
    <test name="Core Integration Tests" time-out="800000">
        <groups>
            <run>
                <include name="failed"/>
            </run>
        </groups>
        &classes;
    </test>
</suite>
</code>```

Listener.xml content is like

```<code><listeners>
    <listener class-name="com.myclass.Listeners.TestListener"/>
</listeners>
</code>```

And classes file is

```<code><classes>
    <class name="com.orders.tc_class1"/>
    <class name="com.orders.tc_class2"/>
</classes>
</code>```

This is part of the error I'm getting

```<code>org.testng.TestNGException:
TestNG by default disables loading DTD from unsecure Urls. If you need to explicitly load the DTD from a http url, please do so by using the JVM argument [-Dtestng.dtd.http=true]
    at org.testng.xml.TestNGContentHandler.resolveEntity(TestNGContentHandler.java:102)
</code>```

答:
I too faced this issue.
I was unable to run the test from my xml file with right click run. So, the solution that I did was change the "" in the xml file to "https://... "
and it solved the issue.
Thanks</p>

Body:
I'm using testng maven and selenium to run my tests, currently I have the following testng.xml file

Looks like the problem is with the &listeners and &classes lines, If I replace those lines with the xml content that I have on the referenced files it runs fine. I have used this in a previous project and it worked fine, not sure why I'm getting this error.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"   [
        <!ENTITY listeners SYSTEM "listeners.xml">
        <!ENTITY classes SYSTEM "classes.xml">
        ]>
<suite name="Local Execution" verbose="5">
    &listeners;
    <test name="Core Integration Tests" time-out="800000">
        <groups>
            <run>
                <include name="failed"/>
            </run>
        </groups>
        &classes;
    </test>
</suite>

Listener.xml content is like

<listeners>
    <listener class-name="com.myclass.Listeners.TestListener"/>
</listeners>

And classes file is

<classes>
    <class name="com.orders.tc_class1"/>
    <class name="com.orders.tc_class2"/>
</classes>

This is part of the error I'm getting

org.testng.TestNGException:
TestNG by default disables loading DTD from unsecure Urls. If you need to explicitly load the DTD from a http url, please do so by using the JVM argument [-Dtestng.dtd.http=true]
    at org.testng.xml.TestNGContentHandler.resolveEntity(TestNGContentHandler.java:102)


问:
Why are some of the secondary options not working for the rules in my .stylelintrc?
I am trying to format my css so there's no more than one empty line between lines, but I don't want that to apply to comments.  The documentation for stylelint has a secondary option that should make this easy, but for some reason it isn't working.

Here's the rule:

```<code>"max-empty-lines": [
      1,
      {
        "ignore": [
          "comments"
        ]
      }
    ],
</code>```

And here's the rest of my .stylelintrc for reference:

```<code>{
  "rules": {
    "at-rule-empty-line-before": "always",
    "at-rule-no-unknown": true,
    "block-closing-brace-empty-line-before": "never",
    "block-closing-brace-newline-before": "always",
    "block-opening-brace-newline-after": "always",
    "block-opening-brace-space-before": "always",
    "block-no-empty": null,
    "color-no-invalid-hex": true,
    "color-hex-case": "upper",
    "color-hex-length": "short",
    "comment-empty-line-before": [
      "always",
      {
        "except": [
          "first-nested"
        ]
      }
    ],
    "comment-no-empty": true,
    "comment-whitespace-inside": "never",
    "custom-property-empty-line-before": "never",
    "custom-property-no-missing-var-function": true,
    "declaration-block-no-duplicate-custom-properties": true,
    "declaration-block-no-duplicate-properties": [
      true,
      {
        "ignore": [
          "consecutive-duplicates-with-different-values"
        ]
      }
    ],
    "declaration-block-no-shorthand-property-overrides": true,
    "declaration-block-semicolon-newline-after": "always",
    "declaration-block-semicolon-newline-before": "never-multi-line",
    "declaration-block-semicolon-space-before": "never",
    "declaration-block-semicolon-space-after": "never-single-line",
    "declaration-block-trailing-semicolon": "always",
    "declaration-colon-space-before": "never",
    "declaration-colon-space-after": "always",
    "declaration-empty-line-before": "never",
    "font-family-no-duplicate-names": true,
    "font-family-no-missing-generic-family-keyword": true,
    "function-calc-no-unspaced-operator": true,
    "function-linear-gradient-no-nonstandard-direction": true,
    "function-no-unknown": true,
    "keyframe-declaration-no-important": true,
    "max-empty-lines": [
      1,
      {
        "ignore": [
          "comments"
        ]
      }
    ],
    "media-feature-name-no-unknown": true,
    "named-grid-areas-no-invalid": true,
    "no-descending-specificity": true,
    "no-duplicate-at-import-rules": true,
    "no-duplicate-selectors": true,
    "no-empty-source": true,
    "no-eol-whitespace": true,
    "no-extra-semicolons": true,
    "no-invalid-double-slash-comments": true,
    "no-invalid-position-at-import-rule": true,
    "no-irregular-whitespace": true,
    "property-no-unknown": true,
    "rule-empty-line-before": "always",
    "selector-list-comma-newline-after": "always",
    "selector-list-comma-newline-before": "never-multi-line",
    "selector-list-comma-space-before": "never",
    "selector-max-empty-lines": 0,
    "selector-pseudo-class-no-unknown": true,
    "selector-pseudo-element-no-unknown": true,
    "selector-type-no-unknown": [
      true,
      {
        "ignore": [
          "custom-elements"
        ]
      }
    ],
    "string-no-newline": true,
    "unit-no-unknown": true
  }
}
</code>```

答:
You are using the secondary option correctly as this demo shows:

```<code>{
  "rules": {
    "max-empty-lines": [1, {"ignore": ["comments"]}]
  }
}
</code>```
```<code>/* comment

*/

a {}

b {}
</code>```

Gives only one error on line 8:

```<code>8:1 error Expected no more than 1 empty line (max-empty-lines)
</code>```

If you aren't seeing this behaviour locally, I suggest reporting a bug in the Stylelint issue tracker.

Body:
I am trying to format my css so there's no more than one empty line between lines, but I don't want that to apply to comments.  The documentation for stylelint has a secondary option that should make this easy, but for some reason it isn't working.

Here's the rule:

"max-empty-lines": [
      1,
      {
        "ignore": [
          "comments"
        ]
      }
    ],

And here's the rest of my .stylelintrc for reference:

{
  "rules": {
    "at-rule-empty-line-before": "always",
    "at-rule-no-unknown": true,
    "block-closing-brace-empty-line-before": "never",
    "block-closing-brace-newline-before": "always",
    "block-opening-brace-newline-after": "always",
    "block-opening-brace-space-before": "always",
    "block-no-empty": null,
    "color-no-invalid-hex": true,
    "color-hex-case": "upper",
    "color-hex-length": "short",
    "comment-empty-line-before": [
      "always",
      {
        "except": [
          "first-nested"
        ]
      }
    ],
    "comment-no-empty": true,
    "comment-whitespace-inside": "never",
    "custom-property-empty-line-before": "never",
    "custom-property-no-missing-var-function": true,
    "declaration-block-no-duplicate-custom-properties": true,
    "declaration-block-no-duplicate-properties": [
      true,
      {
        "ignore": [
          "consecutive-duplicates-with-different-values"
        ]
      }
    ],
    "declaration-block-no-shorthand-property-overrides": true,
    "declaration-block-semicolon-newline-after": "always",
    "declaration-block-semicolon-newline-before": "never-multi-line",
    "declaration-block-semicolon-space-before": "never",
    "declaration-block-semicolon-space-after": "never-single-line",
    "declaration-block-trailing-semicolon": "always",
    "declaration-colon-space-before": "never",
    "declaration-colon-space-after": "always",
    "declaration-empty-line-before": "never",
    "font-family-no-duplicate-names": true,
    "font-family-no-missing-generic-family-keyword": true,
    "function-calc-no-unspaced-operator": true,
    "function-linear-gradient-no-nonstandard-direction": true,
    "function-no-unknown": true,
    "keyframe-declaration-no-important": true,
    "max-empty-lines": [
      1,
      {
        "ignore": [
          "comments"
        ]
      }
    ],
    "media-feature-name-no-unknown": true,
    "named-grid-areas-no-invalid": true,
    "no-descending-specificity": true,
    "no-duplicate-at-import-rules": true,
    "no-duplicate-selectors": true,
    "no-empty-source": true,
    "no-eol-whitespace": true,
    "no-extra-semicolons": true,
    "no-invalid-double-slash-comments": true,
    "no-invalid-position-at-import-rule": true,
    "no-irregular-whitespace": true,
    "property-no-unknown": true,
    "rule-empty-line-before": "always",
    "selector-list-comma-newline-after": "always",
    "selector-list-comma-newline-before": "never-multi-line",
    "selector-list-comma-space-before": "never",
    "selector-max-empty-lines": 0,
    "selector-pseudo-class-no-unknown": true,
    "selector-pseudo-element-no-unknown": true,
    "selector-type-no-unknown": [
      true,
      {
        "ignore": [
          "custom-elements"
        ]
      }
    ],
    "string-no-newline": true,
    "unit-no-unknown": true
  }
}

Body:
You are using the secondary option correctly as this demo shows:

{
  "rules": {
    "max-empty-lines": [1, {"ignore": ["comments"]}]
  }
}

/* comment

*/

a {}

b {}

Gives only one error on line 8:

8:1 error Expected no more than 1 empty line (max-empty-lines)

If you aren't seeing this behaviour locally, I suggest reporting a bug in the Stylelint issue tracker.


问:
sql case in column and where section without repeating the case
I have a sql statement like this but with a very long case expression in it and I need it in the where as well as in the column. Is there a way to use the case without repeating it in the column and where section.</p>
```<code>select * from c.name, (case when c.age = 1 then 0 when c.age = 2 then 1 ... etc else -1 end;)
from customer c
where (case when c.age = 1 then 0 when c.age = 2 then 1 ... etc else -1 end;) > 0
</code>```

答:
Typically you would use a subquery to get around this problem:

SELECT *
FROM
(
    SELECT c.name,
           CASE WHEN c.age = 1 THEN 0 WHEN c.age = 2 THEN 1 ELSE -1 END AS val
    FROM customer c
    INNER JOIN employee e ON c.emp_id = e.id
) t
WHERE val > 0;
```
<p>But in practice if you had a list of age values which get mapped to positive values, you could just use a single level query with a <code>WHERE</code> clause:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT c.name,
       CASE WHEN c.age = 1 THEN 0 WHEN c.age = 2 THEN 1 ELSE -1 END AS val
FROM customer c
WHERE age IN (2, ...);
</code>```

Body:
I have a sql statement like this but with a very long case expression in it and I need it in the where as well as in the column. Is there a way to use the case without repeating it in the column and where section.

select * from c.name, (case when c.age = 1 then 0 when c.age = 2 then 1 ... etc else -1 end;)
from customer c
where (case when c.age = 1 then 0 when c.age = 2 then 1 ... etc else -1 end;) > 0

Body:
Typically you would use a subquery to get around this problem:

SELECT *
FROM
(
    SELECT c.name,
           CASE WHEN c.age = 1 THEN 0 WHEN c.age = 2 THEN 1 ELSE -1 END AS val
    FROM customer c
    INNER JOIN employee e ON c.emp_id = e.id
) t
WHERE val > 0;

But in practice if you had a list of age values which get mapped to positive values, you could just use a single level query with a WHERE clause:

SELECT c.name,
       CASE WHEN c.age = 1 THEN 0 WHEN c.age = 2 THEN 1 ELSE -1 END AS val
FROM customer c
WHERE age IN (2, ...);


问:
Node selenium-webdriver "Error: Timed out waiting for the WebDriver server at"
While following the instructions in the 'Getting Started' section of
the WebDriverJs documentation and after running this snippet from their site:

```<code>var driver = new webdriver.Builder().
   withCapabilities(webdriver.Capabilities.chrome()).
   build();

driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.wait(function() {
 return driver.getTitle().then(function(title) {
   return title === 'webdriver - Google Search';
 });
}, 1000);

driver.quit();
</code>```

I'm getting this error:

```<code>Error: Timed out waiting for the WebDriver server at http://XXX.XXX.X.XXX:60065/
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
==== async task ====
WebDriver.createSession()
</code>```

I'm running OSX Mavericks using the mac32 version of ChromeDriver found here. The chromedriver executable is in my /usr/local/bin directory, and is accessible on my path.

One thing I notice is that when I run chromedriver from the command line, it runs on port 9515, while the node code is looking for it on 60065. However, there shouldn't be any extra configuration required for just running with the chromedriver.

Would anyone have any ideas on why I'm getting this error?

答: I had this error when using new firefox.Service Builder('/path/to/geckodriver'), this error disappeared when I added the path to geckodriver to the variable $PATH.

Body:
While following the instructions in the 'Getting Started' section of
the WebDriverJs documentation and after running this snippet from their site:

var driver = new webdriver.Builder().
   withCapabilities(webdriver.Capabilities.chrome()).
   build();

driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.wait(function() {
 return driver.getTitle().then(function(title) {
   return title === 'webdriver - Google Search';
 });
}, 1000);

driver.quit();

I'm getting this error:

Error: Timed out waiting for the WebDriver server at http://XXX.XXX.X.XXX:60065/
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
    at <anonymous>
==== async task ====
WebDriver.createSession()

I'm running OSX Mavericks using the mac32 version of ChromeDriver found here. The chromedriver executable is in my /usr/local/bin directory, and is accessible on my path.

One thing I notice is that when I run chromedriver from the command line, it runs on port 9515, while the node code is looking for it on 60065. However, there shouldn't be any extra configuration required for just running with the chromedriver.

Would anyone have any ideas on why I'm getting this error?


问:
move assignment from newly constructed object to *this in a member function
Implementing a reset() method, which uses some of the members from this to construct a new object and then move-assign that object to *this.

Questions:

Does this cause any problems? UB or otherwise? (seems fine to me?)

Is there a more idiomatic way?

Destructor and move-assignment operator only implemented to prove what is happening/ The real class has neither. "Rule of 5" not followed, as not needed here.

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <numeric>
#include <ostream>
#include <random>
#include <vector>

struct Thing { // NOLINT Rule of 5 not followed, because debug only
public:
  std::size_t      size;
  std::vector<int> v;

  explicit Thing(std::size_t size_) : size(size_), v(size_) {
    std::cerr << "Thing constructor\n";
    std::iota(v.begin(), v.end(), 1);
  }

  ~Thing() { std::cerr << "Thing destructor\n"; } // purely for debugging

  Thing& operator=(Thing&& other) noexcept {  // purely for debugging
    std::cerr << "Thing Move Assignment operator\n";
    size = other.size;
    v    = std::move(other.v);
    return *this;
  }

  void shuffle() {
    std::shuffle(v.begin(), v.end(), std::mt19937{1}); // NOLINT fixed seed
  }
  void reset() {
    // move assignment operator from a newly constructed object. Constructor uses SOME of the
    // member variables of *this
    *this = Thing(size);
  }

  friend std::ostream& operator<<(std::ostream& os, const Thing& t) {
    os << "[";
    const char* delim = "";
    for (const auto& e: t.v) {
      os << delim << e;
      delim = ",";
    }
    return os << "]";
  }
};

int main() {
  std::cerr << "Before inital construction\n";
  auto t = Thing(10);
  std::cout << t << "\n";
  t.shuffle(); // somehow modify the object
  std::cerr << "Before reset\n";
  std::cout << t << "\n";
  t.reset(); // reset using
  std::cerr << "after reset\n";
  std::cout << t << "\n";
}
```
<p>Output:</p>
```Before inital construction
Thing constructor
[1,2,3,4,5,6,7,8,9,10]
Before reset
[10,1,3,6,8,5,7,4,2,9]
Thing constructor
Thing Move Assignment operator
Thing destructor
after reset
[1,2,3,4,5,6,7,8,9,10]
Thing destructor
```

答:
Does this cause any problems? UB or otherwise? (seems fine to me?)

As long as the move assignment and the constructor are implemented in such a way that it does what you want, then I don't see a problem.

Is there a more idiomatic way?

I would invert the direction of re-use.

```<code>explicit Thing(std::size_t size_) : size(size_), v(size_) {
    reset();
}

void reset() {
    v.resize(size_);
    std::iota(v.begin(), v.end(), 1);
}
</code>```

If size is supposed to always match the size of the vector, then I would recommend removing the member since the size is already stored inside the vector. This has a caveat that in such case reset won't be able to restore a moved-from thing to its earlier size. But that's typically reasonable limitation.

Body:
Implementing a reset() method, which uses some of the members from this to construct a new object and then move-assign that object to *this.

Questions:

Does this cause any problems? UB or otherwise? (seems fine to me?)

Is there a more idiomatic way?

Destructor and move-assignment operator only implemented to prove what is happening/ The real class has neither. "Rule of 5" not followed, as not needed here.

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <numeric>
#include <ostream>
#include <random>
#include <vector>

struct Thing { // NOLINT Rule of 5 not followed, because debug only
public:
  std::size_t      size;
  std::vector<int> v;

  explicit Thing(std::size_t size_) : size(size_), v(size_) {
    std::cerr << "Thing constructor\n";
    std::iota(v.begin(), v.end(), 1);
  }

  ~Thing() { std::cerr << "Thing destructor\n"; } // purely for debugging

  Thing& operator=(Thing&& other) noexcept {  // purely for debugging
    std::cerr << "Thing Move Assignment operator\n";
    size = other.size;
    v    = std::move(other.v);
    return *this;
  }

  void shuffle() {
    std::shuffle(v.begin(), v.end(), std::mt19937{1}); // NOLINT fixed seed
  }
  void reset() {
    // move assignment operator from a newly constructed object. Constructor uses SOME of the
    // member variables of *this
    *this = Thing(size);
  }

  friend std::ostream& operator<<(std::ostream& os, const Thing& t) {
    os << "[";
    const char* delim = "";
    for (const auto& e: t.v) {
      os << delim << e;
      delim = ",";
    }
    return os << "]";
  }
};

int main() {
  std::cerr << "Before inital construction\n";
  auto t = Thing(10);
  std::cout << t << "\n";
  t.shuffle(); // somehow modify the object
  std::cerr << "Before reset\n";
  std::cout << t << "\n";
  t.reset(); // reset using
  std::cerr << "after reset\n";
  std::cout << t << "\n";
}

Output:

Before inital construction
Thing constructor
[1,2,3,4,5,6,7,8,9,10]
Before reset
[10,1,3,6,8,5,7,4,2,9]
Thing constructor
Thing Move Assignment operator
Thing destructor
after reset
[1,2,3,4,5,6,7,8,9,10]
Thing destructor

Body:
Does this cause any problems? UB or otherwise? (seems fine to me?)

As long as the move assignment and the constructor are implemented in such a way that it does what you want, then I don't see a problem.

Is there a more idiomatic way?

I would invert the direction of re-use.

explicit Thing(std::size_t size_) : size(size_), v(size_) {
    reset();
}

void reset() {
    v.resize(size_);
    std::iota(v.begin(), v.end(), 1);
}

If size is supposed to always match the size of the vector, then I would recommend removing the member since the size is already stored inside the vector. This has a caveat that in such case reset won't be able to restore a moved-from thing to its earlier size. But that's typically reasonable limitation.


问:
How to fix "ImportError: DLL load failed" while importing win32api
I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:

```<code>>>> import win32api
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.
</code>```

I'm on Windows 10 Home 64x. I've already tried

```<code>pip install pypiwin32
</code>```

And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I import django, so I think it's a win32api issue only.

```<code>>>> import win32api
</code>```

I expect the output to be none, but the actual output is always that error ^^

答:
As of February 2022, downgrading tot version 303 of pywin32 solves the issue.

Check your pywin32 version:

```<code>pip show pywin32
</code>```

Downgrade to version 300:

```<code>pip install pywin32==300 --upgrade
</code>```

Restart Jupyter

Body:
I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error:

>>> import win32api
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: DLL load failed while importing win32api: The specified module could not be found.

I'm on Windows 10 Home 64x. I've already tried

pip install pypiwin32

And it successfully installs but nothing changes. I tried uninstalling and re-installing python as well. I also tried installing 'django' in the same way and it actually works when I import django, so I think it's a win32api issue only.

>>> import win32api

I expect the output to be none, but the actual output is always that error ^^

Body:
As of February 2022, downgrading tot version 303 of pywin32 solves the issue.

Check your pywin32 version:

pip show pywin32

Downgrade to version 300:

pip install pywin32==300 --upgrade

Restart Jupyter


问:
Zend redirect() is not working with AJAX request?
For example I have an action in Controller.

```<code>public function redirectnowAction() {
   $this->_redirect( '/module/controller/action' );
}
</code>```

When I call above action in normal way then it redirect successfully to desired location But when I call above action by AJAX then it does not redirect to required URL and only show desired page content in firebug.

JS code for AJAX

```<code>jQuery('.AjaxLink').live( 'click', function(event) {
    event.preventDefault();
    // load the href attribute of the link that was clicked
    jQuery.getJSON(this.href, function(snippets) {
        for(var id in snippets) {
            // updated to deal with any type of HTML
            jQuery('#' + id).html( snippets[id] );
        }
    });
});
</code>```

How to redirect to action after AJAX request ?

Thanks

答:
You cannot do it directly, here's what I'd do. In the action called via AJAX, include something like this:

```<code>echo Zend_Json::encode(array('redirect' => '/module/controller/action'));
</code>```

This way, your AJAX call will receive a JSON object as a response. In jQuery's $.ajax() call, you can specify a success event, e.g.:

```<code>'dataType': 'json', // expects to receive a JSON-formatted response
'success': function(data, textStatus, jqXHR) {
    window.location.replace('http://www.example.com' + data.redirect);
}
</code>```

Body:
For example I have an action in Controller.

public function redirectnowAction() {
   $this->_redirect( '/module/controller/action' );
}

When I call above action in normal way then it redirect successfully to desired location But when I call above action by AJAX then it does not redirect to required URL and only show desired page content in firebug.

JS code for AJAX

jQuery('.AjaxLink').live( 'click', function(event) {
    event.preventDefault();
    // load the href attribute of the link that was clicked
    jQuery.getJSON(this.href, function(snippets) {
        for(var id in snippets) {
            // updated to deal with any type of HTML
            jQuery('#' + id).html( snippets[id] );
        }
    });
});

How to redirect to action after AJAX request ?

Thanks

Body:
You cannot do it directly, here's what I'd do. In the action called via AJAX, include something like this:

echo Zend_Json::encode(array('redirect' => '/module/controller/action'));

This way, your AJAX call will receive a JSON object as a response. In jQuery's $.ajax() call, you can specify a success event, e.g.:

'dataType': 'json', // expects to receive a JSON-formatted response
'success': function(data, textStatus, jqXHR) {
    window.location.replace('http://www.example.com' + data.redirect);
}


问:
How to access a react component fiber in whatsapp web from chrome console?
I'm trying to develop a chrome extension that access the conversation of WhatsApp Web. I'm struggling to access the Conversation component state (component that I can see with the React developper tools)

When I try

document.querySelector("#main")['__reactFiber$lwbvlqgcvdi']
```
<p>I get something like this</p>
<pre class="lang-js prettyprint-override"><code>alternate: zu {tag: 5, key: null, elementType: 'div', type: 'div', stateNode: div#main._1fqrG, …}
child: zu {tag: 0, key: '33619488273-1490436851@g.us', stateNode: null, elementType: ƒ, type: ƒ, …}
childLanes: 1
dependencies: null
elementType: "div"
firstEffect: zu {tag: 5, key: null, elementType: 'div', type: 'div', stateNode: div._26lC3, …}
flags: 0
index: 0
key: null
lanes: 0
lastEffect: zu {tag: 1, key: null, stateNode: t, elementType: ƒ, type: ƒ, …}
memoizedProps: {id: 'main', className: '_1fqrG', style: {…}, children: {…}}
memoizedState: null
mode: 0
nextEffect: null
pendingProps: {id: 'main', className: '_1fqrG', style: {…}, children: {…}}
ref: e=> {…}
return: zu {tag: 10, key: null, elementType: {…}, type: {…}, stateNode: null, …}
sibling: zu {tag: 5, key: null, elementType: 'div', type: 'div', stateNode: div, …}
stateNode: div#main._1fqrG
tag: 5
type: "div"
updateQueue: null
[[Prototype]]: Object
</code>```

instead of the following result I get when using the React developer tools $r variable

context: {}
props: {setInterval: ƒ, clearInterval: ƒ, setTimeout: ƒ, clearTimeout: ƒ, requestAnimationFrame: ƒ, …}
refs: {}
state: {chat: g, msgCollection: u, focusCtx: {…}, showConversationPreview: false, animate: false, …}
updater: {isMounted: ƒ, enqueueSetState: ƒ, enqueueReplaceState: ƒ, enqueueForceUpdate: ƒ}
_handleCloseChat: e=> {…}
_handleOpenChat: (e,t,a)=> {…}
_handleOpenChatId: 1
_msgCollectionChanged: (e,t,a,s)=> {…}
_newChatScrollInfo: (e,t)=> {…}
_openedChatInfo: {chat: g, renderedMsgsInfo: {…}, visibleMsgOrder: Array(11), clientHeight: 572}
_reactInternals: zu {tag: 1, key: null, stateNode: y, elementType: ƒ, type: ƒ, …}
_refContainer: {current: t.default}
_windowGainedFocus: ()=> {…}
_windowLostFocus: ()=> {…}
[[Prototype]]: m
```

document.querySelector("#main")['__reactFiber$lwbvlqgcvdi'].stateNodereturns the same element than document.querySelector("#main")['__reactFiber$lwbvlqgcvdi']

document.querySelector("#main")['__reactFiber$lwbvlqgcvdi'].return gives me the context provider wrapping the component

return.stateNode returns null

What do I miss?

答:
I finally figured it out.
It was the great great great great grandparent of the #main element. (Element react developer tools gives me as the matching DOM element for the Conversation component)

Now I know that React developer tools can give the same matching DOM element for different components ^^'

Update

To access the state I was looking for I used the following code :

  document.querySelector("#main")['__reactFiber$lwbvlqgcvdi'].return.return.return.return.return.return.stateNode.state
```

I really found this out of luck as I was crawling up the graph of object out of boredom / despaire / curiosity ^^'

Body:
I'm trying to develop a chrome extension that access the conversation of WhatsApp Web. I'm struggling to access the Conversation component state (component that I can see with the React developper tools)

When I try

document.querySelector("#main")['__reactFiber$lwbvlqgcvdi']

I get something like this

alternate: zu {tag: 5, key: null, elementType: 'div', type: 'div', stateNode: div#main._1fqrG, …}
child: zu {tag: 0, key: '33619488273-1490436851@g.us', stateNode: null, elementType: ƒ, type: ƒ, …}
childLanes: 1
dependencies: null
elementType: "div"
firstEffect: zu {tag: 5, key: null, elementType: 'div', type: 'div', stateNode: div._26lC3, …}
flags: 0
index: 0
key: null
lanes: 0
lastEffect: zu {tag: 1, key: null, stateNode: t, elementType: ƒ, type: ƒ, …}
memoizedProps: {id: 'main', className: '_1fqrG', style: {…}, children: {…}}
memoizedState: null
mode: 0
nextEffect: null
pendingProps: {id: 'main', className: '_1fqrG', style: {…}, children: {…}}
ref: e=> {…}
return: zu {tag: 10, key: null, elementType: {…}, type: {…}, stateNode: null, …}
sibling: zu {tag: 5, key: null, elementType: 'div', type: 'div', stateNode: div, …}
stateNode: div#main._1fqrG
tag: 5
type: "div"
updateQueue: null
[[Prototype]]: Object

instead of the following result I get when using the React developer tools $r variable

context: {}
props: {setInterval: ƒ, clearInterval: ƒ, setTimeout: ƒ, clearTimeout: ƒ, requestAnimationFrame: ƒ, …}
refs: {}
state: {chat: g, msgCollection: u, focusCtx: {…}, showConversationPreview: false, animate: false, …}
updater: {isMounted: ƒ, enqueueSetState: ƒ, enqueueReplaceState: ƒ, enqueueForceUpdate: ƒ}
_handleCloseChat: e=> {…}
_handleOpenChat: (e,t,a)=> {…}
_handleOpenChatId: 1
_msgCollectionChanged: (e,t,a,s)=> {…}
_newChatScrollInfo: (e,t)=> {…}
_openedChatInfo: {chat: g, renderedMsgsInfo: {…}, visibleMsgOrder: Array(11), clientHeight: 572}
_reactInternals: zu {tag: 1, key: null, stateNode: y, elementType: ƒ, type: ƒ, …}
_refContainer: {current: t.default}
_windowGainedFocus: ()=> {…}
_windowLostFocus: ()=> {…}
[[Prototype]]: m

document.querySelector("#main")['__reactFiber$lwbvlqgcvdi'].stateNodereturns the same element than document.querySelector("#main")['__reactFiber$lwbvlqgcvdi']

document.querySelector("#main")['__reactFiber$lwbvlqgcvdi'].return gives me the context provider wrapping the component

return.stateNode returns null

What do I miss?

Body:
I finally figured it out.
It was the great great great great grandparent of the #main element. (Element react developer tools gives me as the matching DOM element for the Conversation component)

Now I know that React developer tools can give the same matching DOM element for different components ^^'

Update

To access the state I was looking for I used the following code :

  document.querySelector("#main")['__reactFiber$lwbvlqgcvdi'].return.return.return.return.return.return.stateNode.state

I really found this out of luck as I was crawling up the graph of object out of boredom / despaire / curiosity ^^'


问:
type 'double' is not a subtype of type 'int' when decoding data from json + returns null
Every time the data has to be decoded it returns null and the exception type 'double' is not a subtype of type 'int'. The problem is the method attached below.

```<code>Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    print(extractedData['title']);
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(),
            steps: data['steps'].cast<String>(),
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
            servings: data['servings'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }
</code>```

Here is my recipe model

```<code>class Recipe with ChangeNotifier {
  String title;
  String id;
  String description;
  File? image;
  bool favorite;
  List<String> ingredients;
  List<String> steps;
  int servings;
  int kcal;
  int p;
  int c;
  int f;

  Recipe({
    required this.title,
    required this.description,
    this.favorite = false,
    required this.id,
    this.image,
    required this.ingredients,
    required this.steps,
    required this.c,
    required this.kcal,
    required this.f,
    required this.p,
    required this.servings,
  });
</code>```

I/flutter (31885): null E/flutter (31885):
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type
'double' is not a subtype of type 'int' E/flutter (31885): #0

RecipeProvider.fetchProducts.
package:recipier/providers/recipes_provider.dart:39 E/flutter (31885):
#1      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8) E/flutter (31885): #2
RecipeProvider.fetchProducts
package:recipier/providers/recipes_provider.dart:30 E/flutter (31885):

答:
So I found a weird solution. Anyone else having this problem, I recommend you try this.</p>
```<code>extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(),
            steps: data['steps'].cast<String>(),
            kcal: double.parse(data['kcal'].toString()).toInt(),
            p: double.parse(data['p'].toString()).toInt(),
            c: double.parse(data['c'].toString()).toInt(),
            f: double.parse(data['f'].toString()).toInt(),
            servings: double.parse(data['servings'].toString()).toInt(),
          ),
        );
      },
    );
</code>```

Body:
Every time the data has to be decoded it returns null and the exception type 'double' is not a subtype of type 'int'. The problem is the method attached below.

Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    print(extractedData['title']);
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(),
            steps: data['steps'].cast<String>(),
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
            servings: data['servings'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }

Here is my recipe model

class Recipe with ChangeNotifier {
  String title;
  String id;
  String description;
  File? image;
  bool favorite;
  List<String> ingredients;
  List<String> steps;
  int servings;
  int kcal;
  int p;
  int c;
  int f;

  Recipe({
    required this.title,
    required this.description,
    this.favorite = false,
    required this.id,
    this.image,
    required this.ingredients,
    required this.steps,
    required this.c,
    required this.kcal,
    required this.f,
    required this.p,
    required this.servings,
  });

I/flutter (31885): null E/flutter (31885):
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type
'double' is not a subtype of type 'int' E/flutter (31885): #0

RecipeProvider.fetchProducts.
package:recipier/providers/recipes_provider.dart:39 E/flutter (31885):
#1      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8) E/flutter (31885): #2
RecipeProvider.fetchProducts
package:recipier/providers/recipes_provider.dart:30 E/flutter (31885):

Body:
So I found a weird solution. Anyone else having this problem, I recommend you try this.

extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(),
            steps: data['steps'].cast<String>(),
            kcal: double.parse(data['kcal'].toString()).toInt(),
            p: double.parse(data['p'].toString()).toInt(),
            c: double.parse(data['c'].toString()).toInt(),
            f: double.parse(data['f'].toString()).toInt(),
            servings: double.parse(data['servings'].toString()).toInt(),
          ),
        );
      },
    );


问:
How to map `Object.values()` over an array of objects nesting objects?
I'm trying to map Object.values() to extract just the values from an array of objects:

const countries = [
    {
        "austria": { value: 1},
        "canada": {value: 2},
        "nepal": { value: 3},
        "india": { value: 4}
    },
    {
        "australia": { value: 10},
        "france": { value: 20},
        "egypt": { value: 40},
        "usa": { value: 20}
    },
    {
        "mexico": { value: 3},
        "germany": { value: 100},
        "southAfrica": { value: 1},
        "china": { value: 10}
    }
]
```
<p>To get:</p>
<pre class="lang-js prettyprint-override"><code>// expected output
[
    {
        "austria": [ 1 ],
        "canada": [ 2 ],
        "nepal": [ 3 ],
        "india": [ 4 ]
    },
    {
        "australia": [ 10 ] ,
        "france": [ 20 ],
        "egypt": [ 40 ],
        "usa": [ 20 ]
    },
    {
        "mexico": [ 3 ],
        "germany": [ 100 ],
        "southAfrica": [ 1 ],
        "china": [ 10 ]
    }
]
</code>```

I tried

Object.values(countries) // returns the same as `countries`
```
<p>and also tried mapping using <code>ramda</code>'s <code>map()</code> to map <code>Object.values()</code> over <code>countries</code></p>
<pre class="lang-js prettyprint-override"><code>const R = require("ramda")

R.map(Object.values, countries)
// gives:
// [
//   [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 } ],
//   [ { value: 10 }, { value: 20 }, { value: 40 }, { value: 20 } ],
//   [ { value: 3 }, { value: 100 }, { value: 1 }, { value: 10 } ]
// ]
</code>```

But I don't want to lose the countries names! How can I utilize either vanilla map or ramda's version to get the expected output?

答:
Using Ramda, you have to use use R.map twice:

To map over the items in the array.

To map over each value of the object.

const countries = [
    {
        "austria": { value: 1},
        "canada": {value: 2},
        "nepal": { value: 3},
        "india": { value: 4}
    },
    {
        "australia": { value: 10},
        "france": { value: 20},
        "egypt": { value: 40},
        "usa": { value: 20}
    },
    {
        "mexico": { value: 3},
        "germany": { value: 100},
        "southAfrica": { value: 1},
        "china": { value: 10}
    }
]

const result = R.map(R.map(Object.values))(countries);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important }</code>```

```

Body:
I'm trying to map Object.values() to extract just the values from an array of objects:

const countries = [
    {
        "austria": { value: 1},
        "canada": {value: 2},
        "nepal": { value: 3},
        "india": { value: 4}
    },
    {
        "australia": { value: 10},
        "france": { value: 20},
        "egypt": { value: 40},
        "usa": { value: 20}
    },
    {
        "mexico": { value: 3},
        "germany": { value: 100},
        "southAfrica": { value: 1},
        "china": { value: 10}
    }
]

To get:

// expected output
[
    {
        "austria": [ 1 ],
        "canada": [ 2 ],
        "nepal": [ 3 ],
        "india": [ 4 ]
    },
    {
        "australia": [ 10 ] ,
        "france": [ 20 ],
        "egypt": [ 40 ],
        "usa": [ 20 ]
    },
    {
        "mexico": [ 3 ],
        "germany": [ 100 ],
        "southAfrica": [ 1 ],
        "china": [ 10 ]
    }
]

I tried

Object.values(countries) // returns the same as `countries`

and also tried mapping using ramda's map() to map Object.values() over countries

const R = require("ramda")

R.map(Object.values, countries)
// gives:
// [
//   [ { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 } ],
//   [ { value: 10 }, { value: 20 }, { value: 40 }, { value: 20 } ],
//   [ { value: 3 }, { value: 100 }, { value: 1 }, { value: 10 } ]
// ]

But I don't want to lose the countries names! How can I utilize either vanilla map or ramda's version to get the expected output?

Body:
Using Ramda, you have to use use R.map twice:

To map over the items in the array.

To map over each value of the object.

const countries = [
    {
        "austria": { value: 1},
        "canada": {value: 2},
        "nepal": { value: 3},
        "india": { value: 4}
    },
    {
        "australia": { value: 10},
        "france": { value: 20},
        "egypt": { value: 40},
        "usa": { value: 20}
    },
    {
        "mexico": { value: 3},
        "germany": { value: 100},
        "southAfrica": { value: 1},
        "china": { value: 10}
    }
]

const result = R.map(R.map(Object.values))(countries);

console.log(result);

.as-console-wrapper { max-height: 100% !important }

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>


问:
How is correct to write connection string in c# web API on .NET Core?
I write my connection string like that:

{
  "ConnectionStrings": {
    "AppCon": "Data Source=192.168.1.24:3306; Initial Catalog=dbName; User Id=UName; Password=Pass"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
```
<p>When I want to navigate in the url address I receive error:</p>
<blockquote>
<p>SocketException: No such host is known.</p>
</blockquote>
<p>and the debugger stuck at this method:</p>
<pre class="lang-cs prettyprint-override"><code>[HttpGet]
public JsonResult Get()
{
    string query = @"SELECT Station, Ime FROM auto_q_stations;";

    DataTable table = new DataTable();

    string sqlDataSource = _configuration.GetConnectionString("AppCon");

    MySqlDataReader myReader;

    using(MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using(MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myReader = myCommand.ExecuteReader();
            table.Load(myReader);

            myReader.Close();
            mycon.Close();
        }
    }
    return new JsonResult(table);
}
</code>```

at this line:

mycon.Open();
```

What do I need to do to properly load my database?

答: You can separate Data Source and Port values as mentioned above, also ',' instead of ':' delimiter should work fine ("Data Source=192.168.1.24,3306;")</p>

Body:
I write my connection string like that:

{
  "ConnectionStrings": {
    "AppCon": "Data Source=192.168.1.24:3306; Initial Catalog=dbName; User Id=UName; Password=Pass"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"

When I want to navigate in the url address I receive error:

SocketException: No such host is known.

and the debugger stuck at this method:

[HttpGet]
public JsonResult Get()
{
    string query = @"SELECT Station, Ime FROM auto_q_stations;";

    DataTable table = new DataTable();

    string sqlDataSource = _configuration.GetConnectionString("AppCon");

    MySqlDataReader myReader;

    using(MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using(MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myReader = myCommand.ExecuteReader();
            table.Load(myReader);

            myReader.Close();
            mycon.Close();
        }
    }
    return new JsonResult(table);
}

at this line:

mycon.Open();

What do I need to do to properly load my database?


问:
Django response Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
my model has attributes fields as file and the person who uploaded it ,in my case i would want to show the error no file found on my website front end when there is no data in model but instead it is taking me to this error i have implemented my code like this</p>
```<code>@api_view(('GET',))
def template_view(request):
    data = Mymodel.objects.first()
    try:
        if data:
            response = HttpResponse(
                data.file,
                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, '
                             'application/vnd.ms-excel',

            )
            return response
    except FileNotFoundError:
        raise ValueError('No file found')
</code>```

答:
Perhaps instead of re-raising a ValueError, you can return a 400 error
e.g.

@api_view(('GET',))
def template_view(request):
    data = Mymodel.objects.first()
    try:
        response = HttpResponse(
            data.file,
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, '
                             'application/vnd.ms-excel',

        )
        return response
    except (FileNotFoundError, AttributeError):
        return HttpResponse("No File Found", status=400)
```

I'd also catch the AttributeError rather than put an if statement for the data

Body:
my model has attributes fields as file and the person who uploaded it ,in my case i would want to show the error no file found on my website front end when there is no data in model but instead it is taking me to this error i have implemented my code like this

@api_view(('GET',))
def template_view(request):
    data = Mymodel.objects.first()
    try:
        if data:
            response = HttpResponse(
                data.file,
                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, '
                             'application/vnd.ms-excel',

            )
            return response
    except FileNotFoundError:
        raise ValueError('No file found')

Body:
Perhaps instead of re-raising a ValueError, you can return a 400 error
e.g.

@api_view(('GET',))
def template_view(request):
    data = Mymodel.objects.first()
    try:
        response = HttpResponse(
            data.file,
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, '
                             'application/vnd.ms-excel',

        )
        return response
    except (FileNotFoundError, AttributeError):
        return HttpResponse("No File Found", status=400)

I'd also catch the AttributeError rather than put an if statement for the data


问:
jQuery Ajax and XSL
Could I ask what could possible be a stupid question. </p>

<p>I currently use an asp.Net framework to pull data from a sqlService DB in xml format and then shape it using xsl. I’m interested in using ajax to do a few of the takes that I’m currently doing with a standard .net/xml/xsl deal. Is it possible to use xsl with jQuery/Ajax? Like I say, could be a stupid question, but thought I would ask anyhow. Big thanks. Andy. </p>

答: i think you are looking for jQuery XSLT Plugin

Title: jQuery Ajax and XSL

Body:
Could I ask what could possible be a stupid question.

I currently use an asp.Net framework to pull data from a sqlService DB in xml format and then shape it using xsl. I’m interested in using ajax to do a few of the takes that I’m currently doing with a standard .net/xml/xsl deal. Is it possible to use xsl with jQuery/Ajax? Like I say, could be a stupid question, but thought I would ask anyhow. Big thanks. Andy.